one-to-many-bidirectional
one-to-many-bidirectional
association
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.
• 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 :
• The inverse side of a bidirectional relationship must refer to its owning side(Entity
designates the property or field in the entity that is the owner of the relationship.
the mappedBy element. The many side is always the owning side of the relationship.
• For @OneToOne bidirectional relationships, the owning side corresponds to the side
• For @ManyToMany bidirectional relationships, either side may be the owning side.