Skip to content
Advertisement

Create relationship between 2 tables JPA

Need help with setting up table relationships. So, there are 2 entities – Section and Period. 1 Section has many Period, but 1 Period do not belongs to any specific Section. I implemented this relationship as follows: created an additional table SectionCodes with an external key on Section (more in diagram)

diagram

Section class:

SectionPeriod:

This works fine, but there is a problem – it turns out that every Section entity has a SectionPeriod list, and SectionPerid has a Section – so there is loop. Is there an easy way to perform this? Ideally, it should be just List of Period in Section class or at least Integer[] of periodCodes.

Advertisement

Answer

To model the Many To Many relationship between Period and Section, you have 2 choices:

  1. Use 2 Entities (Period, Section), and use the @ManyToMany annotation in one of these entities. This will autogenerate the Join Table which will have a composite primary key. This is not recommended.
  2. Use 3 Entities, and this way you can think the “ManyToMany” as having two OneToMany relationships (1 Period – Many “PeriodSection” AND 1 Section – Many “PeriodSection”). This is recommended because this way you will have a PK and you can easily add more columns to the PeriodSection (** Note: instead of PeriodSection, the Entity and Table should have a meaninful name, but i’ll leave that to you)

Using the second choice:

Period:

PeriodSection:

Section:

You can play around with the fetch and cascade strategies, to check which is best for your app. Hope this helped

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement