Hibernate One to Many Mapping (Annotation) Example

In our previous discussion we came across Hibernate One to One Mapping using Annotation. In this particular blog we will see what is hibernate one to many relationship and how to implement it using Annotations. We will demonstrate the relationship by taking two model classes 'Student' and 'StudentMarks' and try to establish a one to many relationship in between them.


Hibernate One to Many Relationship



Database Setup


-- Dumping database structure for hibernate_db
CREATE DATABASE IF NOT EXISTS `hibernate_db` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `hibernate_db`;


-- Dumping structure for table hibernate_db.marks_details
CREATE TABLE IF NOT EXISTS `marks_details` (
`student_id` bigint(100) NOT NULL,
`test_id` bigint(100) NOT NULL AUTO_INCREMENT,
`subject` varchar(100) DEFAULT NULL,
`max_marks` varchar(100) DEFAULT NULL,
`marks_obtained` varchar(100) DEFAULT NULL,
`result` varchar(100) DEFAULT NULL,
PRIMARY KEY (`test_id`),
KEY `FK_marks_details_student` (`student_id`),
CONSTRAINT `FK_marks_details_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Data exporting was unselected.


-- Dumping structure for table hibernate_db.student
CREATE TABLE IF NOT EXISTS `student` (
`student_id` bigint(100) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



Project Structure



Dependencies used in 'Hibernate one to many Mappings'

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
 <modelVersion>4.0.0</modelVersion>  
 <groupId>com.beingjavaguys.hbn</groupId>  
 <artifactId>HibernateOneToMany</artifactId>  
 <packaging>jar</packaging>  
 <version>1.0-SNAPSHOT</version>  
 <name>HibernateOneToMany</name>  
 <url>http://maven.apache.org</url>  
 <dependencies>  
   
  <dependency>  
   <groupId>mysql</groupId>  
   <artifactId>mysql-connector-java</artifactId>  
   <version>5.1.6</version>  
  </dependency>  
  
  <dependency>  
   <groupId>javax.transaction</groupId>  
   <artifactId>jta</artifactId>  
   <version>1.1</version>  
  </dependency>  
  
  <dependency>  
   <groupId>javassist</groupId>  
   <artifactId>javassist</artifactId>  
   <version>3.12.1.GA</version>  
  </dependency>  
  
  <dependency>  
   <groupId>org.hibernate</groupId>  
   <artifactId>hibernate-annotations</artifactId>  
   <version>3.5.0-Final</version>  
  </dependency>  
  
  <dependency>  
   <groupId>org.slf4j</groupId>  
   <artifactId>slf4j-api</artifactId>  
   <version>1.7.5</version>  
  </dependency>  
  
  <dependency>  
   <groupId>org.slf4j</groupId>  
   <artifactId>slf4j-simple</artifactId>  
   <version>1.7.5</version>  
  </dependency>  
    
 </dependencies>  
</project> 


\src\main\resources\hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC  
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
   
<hibernate-configuration>  
<session-factory>  
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>  
    <property name="hibernate.connection.username">root</property>  
    <property name="hibernate.connection.password">root</property>  
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
    <property name="show_sql">true</property>  
    <mapping class="com.beingjavaguys.domain.Student" />  
    <mapping class="com.beingjavaguys.domain.MarksDetails" />  
</session-factory>  
</hibernate-configuration>  


\src\main\java\com\beingjavaguys\domain\Student.java

package com.beingjavaguys.domain;  
  
/** 
 * @author Nagesh Chauhan 
 * 
 */  
  
import java.util.Set;  
  
import javax.persistence.Column;  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.Id;  
import javax.persistence.JoinColumn;  
import javax.persistence.MappedSuperclass;  
import javax.persistence.OneToMany;  
import javax.persistence.Table;  
  
@Entity  
@Table(name = "student")  
public class Student {  
  
 @Id  
 @GeneratedValue  
 @Column(name = "student_id")  
 private long id;  
  
 @Column(name = "first_name")  
 private String firstName;  
  
 @Column(name = "last_name")  
 private String lastName;  
  
 @Column(name = "email")  
 private String email;  
  
 @Column(name = "phone")  
 private String phone;  
  
 @OneToMany(mappedBy = "student")  
 private Set<marksdetails> marksDetails;  
  
 public Student() {  
  
 }  
  
 public Student(String firstName, String lastName, String email, String phone) {  
  this.firstName = firstName;  
  this.lastName = lastName;  
  this.phone = phone;  
  this.email = email;  
 }  
  
 public long getId() {  
  return id;  
 }  
  
 public void setId(long id) {  
  this.id = id;  
 }  
  
 public String getFirstName() {  
  return firstName;  
 }  
  
 public void setFirstName(String firstName) {  
  this.firstName = firstName;  
 }  
  
 public String getLastName() {  
  return lastName;  
 }  
  
 public void setLastName(String lastName) {  
  this.lastName = lastName;  
 }  
  
 public String getEmail() {  
  return email;  
 }  
  
 public void setEmail(String email) {  
  this.email = email;  
 }  
  
 public String getPhone() {  
  return phone;  
 }  
  
 public void setPhone(String phone) {  
  this.phone = phone;  
 }  
  
 public Set<marksdetails> getMarksDetails() {  
  return marksDetails;  
 }  
  
 public void setMarksDetails(Set<marksdetails> marksDetails) {  
  this.marksDetails = marksDetails;  
 }  
  
}  


\src\main\java\com\beingjavaguys\domain\MarksDetails.java

package com.beingjavaguys.domain;  
  
import javax.persistence.Column;  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.Id;  
import javax.persistence.JoinColumn;  
import javax.persistence.ManyToOne;  
import javax.persistence.Table;  
  
@Entity  
@Table(name = "marks_details")  
public class MarksDetails {  
  
 @Id  
 @GeneratedValue  
 @Column(name = "test_id")  
 private long testId;  
  
 @Column(name = "subject")  
 private String subject;  
  
 @Column(name = "max_marks")  
 private String maxMarks;  
  
 @Column(name = "marks_obtained")  
 private String marksObtained;  
  
 @Column(name = "result")  
 private String result;  
  
 @ManyToOne  
 @JoinColumn(name = "student_id")  
 private Student student;  
  
 public MarksDetails() {  
 }  
  
 public MarksDetails(String subject, String maxMarks, String marksObtained,  
   String result) {  
  this.subject = subject;  
  this.maxMarks = maxMarks;  
  this.marksObtained = marksObtained;  
  this.result = result;  
 }  
  
 public long getTestId() {  
  return testId;  
 }  
  
 public void setTestId(long testId) {  
  this.testId = testId;  
 }  
  
 public String getSubject() {  
  return subject;  
 }  
  
 public void setSubject(String subject) {  
  this.subject = subject;  
 }  
  
 public String getMaxMarks() {  
  return maxMarks;  
 }  
  
 public void setMaxMarks(String maxMarks) {  
  this.maxMarks = maxMarks;  
 }  
  
 public String getMarksObtained() {  
  return marksObtained;  
 }  
  
 public void setMarksObtained(String marksObtained) {  
  this.marksObtained = marksObtained;  
 }  
  
 public String getResult() {  
  return result;  
 }  
  
 public void setResult(String result) {  
  this.result = result;  
 }  
  
 public Student getStudent() {  
  return student;  
 }  
  
 public void setStudent(Student student) {  
  this.student = student;  
 }  
  
}  


\src\main\java\com\beingjavaguys\hbn\HibernateUtils.java

package com.beingjavaguys.hbn;  
  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.AnnotationConfiguration;  
  
public class HibernateUtils {  
  
 private static final SessionFactory sessionFactory = buildSessionFactory();  
  
 private static SessionFactory buildSessionFactory() {  
  try {  
   // Create the SessionFactory from hibernate.cfg.xml  
   return new AnnotationConfiguration().configure()  
     .buildSessionFactory();  
  
  } catch (Throwable ex) {  
   System.err.println("Initial SessionFactory creation failed." + ex);  
   throw new ExceptionInInitializerError(ex);  
  }  
 }  
  
 public static SessionFactory getSessionFactory() {  
  return sessionFactory;  
 }  
}  


Implementation class code

\src\main\java\com\beingjavaguys\hbn\App.java

package com.beingjavaguys.hbn;  
  
/** 
 * @author Nagesh Chauhan 
 * 
 */  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
  
import com.beingjavaguys.domain.Student;  
import com.beingjavaguys.domain.MarksDetails;  
  
public class App {  
 public static void main(String[] args) {  
  SessionFactory sf = HibernateUtils.getSessionFactory();  
  Session session = sf.openSession();  
  
  session.beginTransaction();  
  
  Student student = new Student("Nagesh", "Chauhan",  
    "beingjavaguy@gmail.com", "8789876765");  
  session.save(student);  
  
  MarksDetails marksDetails1 = new MarksDetails("Maths", "100", "87",  
    "Passed");  
  MarksDetails marksDetails2 = new MarksDetails("Science", "100", "90",  
    "Passed");  
  MarksDetails marksDetails3 = new MarksDetails("English", "100", "85",  
    "Passed");  
  
  marksDetails1.setStudent(student);  
  marksDetails2.setStudent(student);  
  marksDetails3.setStudent(student);  
  
  session.save(marksDetails1);  
  session.save(marksDetails2);  
  session.save(marksDetails3);  
  
  session.getTransaction().commit();  
  session.close();  
 }  
}  

Table structure after implementation






In this particular blog we came across 'Hibernate One to Many mapping and, implementation using annotations'. In upcoming blogs we will see 'Hibernate Many to Many mapping' and Other Implementations in Java.