Home Hibernate one-to-many bidirectional association

one-to-many bidirectional association

- Advertisement -

In a relational database in a one-to-many relationship, a row in table X can have  more than one matching row in table Y.

In Object oriented programming, one instance of entity refers to multiple instances of another entity in the  relation called one-to-many relation.

In this tutorial used the relationship between Engineering Branch and Students. In an Engineering college each Branch have many Students.

what is bidirectional?

  • Bidirectional relationship provides navigational access in both directions, so that you can access the other side entity without explicit queries.

one-to-many Tables structure in Database :

one-to-many association

Technologies Used in following example :

  • JPA 2.1
  • Hibernate 5.2.6
  • MySql 8.0
  • Maven 3
  • Spring Tool Suite (STS) 3.9.8
  • Java 1.8

Student.java mapping :

/**
 * The persistent class for the STUDENT database table.
 * 
 */
@Entity
public class Student implements Serializable {
    private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    private int id;
 
    @Column(name="CONTACT_NO")
    private String contactNo;
 
    private String fname;
 
    private String lname;
 
      /**
       * @ManyToOne is used to insert manyeth (numerically one, not many) record that to associate with one record of other table
       */
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="BRANCH_ID")
    private Branch branch; 
 
//Setters and getters

Branch.java mapping :

/**
 * The persistent class for the BRANCH database table.
 * 
 */
@Entity
public class Branch implements Serializable {
    private static final long serialVersionUID = 1L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name="BRANCH_ID")
    private int branchId;
 
    @Column(name="BRANCH_NAME")
    private String branchName;
 
    @Column(name="BRANCH_SHORT_NAME")
    private String branchShortName;
 
    private String description;
 
    //bi-directional many-to-one association to Student
    @OneToMany(mappedBy="branch", cascade={CascadeType.ALL})
    private List students;
 
//Setters and getters

Cascade :

  • Whenever rows in the parent table manipulated (inserted, updated, deleted) the respective rows of the child table with a matching key column will be manipulated as well. This is called Cascade in Database.
  • JPA translates entity state transitions to database DML statements.

@JoinColumn :

  • @JoinColumn Specifies a column for joining an entity association or element collection. The annotation @JoinColumn indicates that this entity is the owner of the relationship. That is the corresponding table has a column with a foreign key to the referenced table.

To Understand Cascade and @JoinColumn mapping in entity associations see :
Key points to understand associations

mappedBy :

The mappedBy element defines a bidirectional relationship. This attribute allows you to refer the associated entities from both sides.

one-to-many bidirectional association testing :

/**
 * JPA One-To-Many BiDirectional
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        EntityManagerFactory emf = null;
        EntityManager entityManager = null;
        EntityTransaction transaction = null;
        
        try{
            emf = Persistence.createEntityManagerFactory("jbd-pu");
            entityManager = emf.createEntityManager();
            transaction = entityManager.getTransaction();
            transaction.begin();
            
            Branch branch = new Branch();
            branch.setBranchShortName("CSE");
            branch.setBranchName("Computer Science and Engineering");
            branch.setDescription("CSE department offers courses under ambitious curricula in computer science and computer engineering..");
            List<Student> students = new ArrayList<Student>();
            branch.setStudents(students);
            branch.addStudent(getStudent1());
            branch.addStudent(getStudent2());
            //Branch object having all the information (Branch and Students)
            entityManager.persist(branch);
            transaction.commit();
            
            Student retrivedStudent = entityManager.find(Student.class, branch.getStudents().get(0).getId());
            System.err.println("Branch Name: "+retrivedStudent.getBranch().getBranchName());
        }catch(Exception e){
            transaction.rollback();
            e.printStackTrace();
        }finally{
            entityManager.close();
            emf.close();
        }
    }
    
    private static Student getStudent1(){
        Student student = new Student();
        student.setFname("Peter");
        student.setLname("Milanovich");
        student.setContactNo("+1-408-575-1317");
        
        return student;
    }
    private static Student getStudent2(){
        Student student = new Student();
        student.setFname("Rosy");
        student.setLname("Larsen");
        student.setContactNo("+1-408-575-1219");
        
        return student;
    }

 Output :

INFO - HHH000400: Using dialect: org.hibernate.dialect.MySQLInnoDBDialect
INFO - HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into Branch (BRANCH_NAME, BRANCH_SHORT_NAME, description) values (?, ?, ?)
Hibernate: insert into Student (BRANCH_ID, CONTACT_NO, fname, lname) values (?, ?, ?, ?)
Hibernate: insert into Student (BRANCH_ID, CONTACT_NO, fname, lname) values (?, ?, ?, ?)
Branch Name: Computer Science and Engineering
INFO - HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_JBD]

Download Application – JPA-OneToMany-BiDirection.zip (15 KB)

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories