Wednesday, 5 December 2018

Hibernate Many-To-One Bidirectional


  1. One table has a foreign key column that references the primary key of associated table.In Bidirectional relationship, both side navigation is possible.
  2. We are discussing an example of Student and University relationship. Many student can enroll at one University. And one University can have many students. 
  3. @Entity @Table(name = "STUDENT") public class Student { @Id @GeneratedValue @Column(name = "STUDENT_ID") private long id; @Column(name = "FIRST_NAME") private String firstName; @ManyToOne(optional = false) @JoinColumn(name = "UNIVERSITY_ID") private University university; ------------------------ ------------------------ } @Entity @Table(name = "UNIVERSITY") public class University { @Id @GeneratedValue @Column(name = "UNIVERSITY_ID") private long id; @Column(name = "NAME") private String name; @Column(name = "COUNTRY") private String country; @OneToMany(mappedBy = "university", cascade = CascadeType.ALL) private List students; }
  4. @JoinColumn says that Student table will contain a separate column UNIVERSITY_ID which will eventually act as a foreign key reference to primary key of University table

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *