Uni-directional: The owning class, Foo, maintains a list of Bars. In the database, Bars will have a foreign key to Foo.
<code class="java">@Entity public class Foo { @OneToMany private List<Bar> bars; } @Entity public class Bar { @ManyToOne @JoinColumn(name="fooId") private Foo foo; }</code>
Bidirectional: Both Foo and Bar maintain references to each other.
<code class="java">@Entity public class Foo { @OneToMany(mappedBy="foo") private List<Bar> bars; } @Entity public class Bar { @ManyToOne @JoinColumn(name="fooId") private Foo foo; }</code>
Uni-directional: The owning class, Bar, has a reference to Foo. In the database, Foo will have a foreign key to Bar.
<code class="java">@Entity public class Bar { @ManyToOne @JoinColumn(name="fooId") private Foo foo; } @Entity public class Foo { // No corresponding mapping to Bar }</code>
Bidirectional: Both Foo and Bar maintain references to each other.
<code class="java">@Entity public class Bar { @ManyToOne @JoinColumn(name="fooId") private Foo foo; } @Entity public class Foo { @OneToMany(mappedBy="foo") private List<Bar> bars; }</code>
Using a bridge table: Creates a join table to store the relationships.
<code class="java">@Entity public class Foo { @ManyToMany @JoinTable(name="FOO_BAR", joinColumns = @JoinColumn(name="fooId"), inverseJoinColumns = @JoinColumn(name="barId")) private List<Bar> bars; } @Entity public class Bar { @ManyToMany @JoinTable(name="FOO_BAR", joinColumns = @JoinColumn(name="barId"), inverseJoinColumns = @JoinColumn(name="fooId")) private List<Foo> foos; }</code>
The above is the detailed content of How can I leverage Hibernate and Spring annotations to establish and manage one-to-many, many-to-one, and many-to-many relationships between entities?. For more information, please follow other related articles on the PHP Chinese website!