Wednesday 6 March 2019

Hibernate Mapping One-to-Many using Annotations

In this example you will learn how to map one-to-many relationship using Hibernate Annotations. Consider the following relationship between Student and Phone entity.
According to the relationship a student can have any number of phone numbers.
To create this relationship you need to have a STUDENTPHONE and STUDENT_PHONE table. The relational model is shown below.
To create the STUDENT and PHONE table you need to create the following Java Class files.
Student class is used to create the STUDENT and STUDENT_PHONE table.
package com.vaannila.student;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class Student {

 private long studentId;
 private String studentName;
 private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);

 public Student() {
 }

 public Student(String studentName, Set<Phone> studentPhoneNumbers) {
  this.studentName = studentName;
  this.studentPhoneNumbers = studentPhoneNumbers;
 }

 @Id
 @GeneratedValue
 @Column(name = "STUDENT_ID")
 public long getStudentId() {
  return this.studentId;
 }

 public void setStudentId(long studentId) {
  this.studentId = studentId;
 }

 @Column(name = "STUDENT_NAME", nullable = false, length = 100)
 public String getStudentName() {
  return this.studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

 @OneToMany(cascade = CascadeType.ALL)
 @JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "PHONE_ID") })
 public Set<Phone> getStudentPhoneNumbers() {
  return this.studentPhoneNumbers;
 }

 public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {
  this.studentPhoneNumbers = studentPhoneNumbers;
 }

}
The @OneToMany annotation is used to create the one-to-many relationship between the Student and Phone entities. The @JoinTable annotation is used to create the STUDENT_PHONE link table and @JoinColumn annotation is used to refer the linking columns in both the tables.
Phone class is used to create the PHONE table.
package com.vaannila.student;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "PHONE")
public class Phone {

 private long phoneId;
 private String phoneType;
 private String phoneNumber;

 public Phone() {
 }

 public Phone(String phoneType, String phoneNumber) {
  this.phoneType = phoneType;
  this.phoneNumber = phoneNumber;
 }
 
 @Id
 @GeneratedValue
 @Column(name = "PHONE_ID")
 public long getPhoneId() {
  return this.phoneId;
 }

 public void setPhoneId(long phoneId) {
  this.phoneId = phoneId;
 }

 @Column(name = "PHONE_TYPE", nullable = false, length=10)
 public String getPhoneType() {
  return this.phoneType;
 }

 public void setPhoneType(String phoneType) {
  this.phoneType = phoneType;
 }
 
 @Column(name = "PHONE_NUMBER", nullable = false, length=15)
 public String getPhoneNumber() {
  return this.phoneNumber;
 }

 public void setPhoneNumber(String phoneNumber) {
  this.phoneNumber = phoneNumber;
 }

}
Now create the hibernate configuration file with the Student and Phone class mapping.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping class="com.vaannila.student.Student" />
        <mapping class="com.vaannila.student.Phone" />
    </session-factory>
</hibernate-configuration>
Create the Main class to run the example.
package com.vaannila.student;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.vaannila.util.HibernateUtil;

public class Main {

 public static void main(String[] args) {
  Session session = HibernateUtil.getSessionFactory().openSession();
  Transaction transaction = null;
  try {
   transaction = session.beginTransaction();
   
   Set<Phone> phoneNumbers = new HashSet<Phone>();
   phoneNumbers.add(new Phone("house","32354353"));
   phoneNumbers.add(new Phone("mobile","9889343423"));
   
   Student student = new Student("Eswar", phoneNumbers);
   session.save(student);
   
   transaction.commit();
  } catch (HibernateException e) {
   transaction.rollback();
   e.printStackTrace();
  } finally {
   session.close();
  }

 }

}
On executing the Main class you will see the following output.
The STUDENT table has one record.
The PHONE table has two records.
The STUDENT_PHONE table has two records to link the student and phone numbers.
A single student record points to two phone numbers, this illustrates the one-to-many mapping.
The folder structure of the example is shown below.

No comments:

Post a Comment

Unity Top Download

Latest post

An Introduction to Hybris from basics

An Introduction to Hybris from basics:  -- ecommerce site and PCM(Product content Management) solutions. eg. croma website.  -- having sear...

Popular posts