Hibernate – one-to-many unidirectional association

0
3747

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.

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;// if Field name and Column name is same no need to map with annotation
 
    private String lname;// default mapping is field name
 
//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;
 
    //uni-directional one-to-many association to Student
    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="BRANCH_ID", nullable=false)
    private List students; // Each branch have many Students (list of)
 
//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 MARKDOWN_HASHf6fe5d6d260954e3d74370aaeb356271MARKDOWN_HASH 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

App.java- Testing the above mapping :

/**
 * JPA One-To-Many Unidirectional
 *
 */
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 students = new ArrayList();
            students.add(getStudent1());
            students.add(getStudent2());
            branch.setStudents(students);
            
            //Branch object having all the information (Branch and Students)
            entityManager.persist(branch);
            transaction.commit();
        }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 (CONTACT_NO, fname, lname, BRANCH_ID) values (?, ?, ?, ?)
Hibernate: insert into Student (CONTACT_NO, fname, lname, BRANCH_ID) values (?, ?, ?, ?)
Hibernate: update Student set BRANCH_ID=? where id=?
Hibernate: update Student set BRANCH_ID=? where id=?
INFO - HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_JBD]

Download Application – JPA-OneMany-UniDirection.zip (14 KB)

LEAVE A REPLY

Please enter your comment!
Please enter your name here