Hibernate modelling a N:N Relationship

database-designhibernate

Lets say that we have two entities
Entities:

  • Bus (idBus*)
  • Stop (idStop*,stopDescription)

Where a Bus passes from many Stops and vice versa, therefore the cardinality is N:N.

My question arises from the fact that when we consider to know the idStop and the idBus then we will also know a number of attributes like Direction,NextStopID, TimeOfArrival
How should i map those attributes?

My thought is to make a bridge table having idStop and idBus as Foreign Keys and a number of extra attributes that are not present in either the Bus or the Stop table, but I don't know if this is doable or the correct way to go.

Any thoughts?

Best Answer

Yes, a bridge table (also known as junction table, mapping table etc.) is a perfectly sensible solution in this case, and it is common for a bridge table to have other attributes beside the references to the tables being connected.

As a stationary object, a stop is just a place, which has coordinates and may also have a fixed name as well as some other properties. As a part of a route, though, it can be assigned the additional attributes you have mentioned that would depend on the route, i.e. on the specific bus number. Those would need to be stored in a different table, the one that would link the stop and the route.

So, if by "bus" you mean "bus number" (or "bus route", "bus line"), then by all means create a dedicated table with references to Bus and Stop and with whatever additional attributes you deem necessary. Note, though, that if Bus is meant to store information about specific buses (vehicles), then I would consider creating another entity (called Route perhaps) that I would link to in the bridge table. Bus would then probably reference that new entity, either directly or, again, through another bridge table (in case vehicles were allowed to work alternately on different lines).