0% found this document useful (0 votes)
26 views

one-to-many-bidirectional

Uploaded by

Mohamamd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

one-to-many-bidirectional

Uploaded by

Mohamamd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

one-to-many bidirectional

association

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 :

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)

Bidirectional relationships must follow these rules.

• The inverse side of a bidirectional relationship must refer to its owning side(Entity

which contains the foreign key) by using the mappedBy element of


the @OneToOne, @OneToMany, or @ManyToMany annotation. The mappedBy element

designates the property or field in the entity that is the owner of the relationship.

• The many side of @ManyToOne bidirectional relationships must not define

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

that contains @JoinColumn i.e the corresponding foreign key.

• For @ManyToMany bidirectional relationships, either side may be the owning side.

You might also like