Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Tuesday, 3 September 2013

Hibernate One to One Mapping (Annotation) Example

In our previous discussion we came across 'Hibernate Hello World Example with Annotations '. In this particular blog we will see what is hibernate one to one relationship and how to implement it using Annotatons. We will demonstrate the relationship by taking two model classes 'Student' and 'StudentAddress' and try to establish a one to one relationship in between them.


Hibernate One To One Ralationship

According to the one to one relationship each student entry should have a unique address entry in student_entry table.



Database Setup

We have created two tables 'student' and 'student_address', every student have an associated address in 'student_address' table. No student can have more than one address entry in 'student_address' table. These two tables are mapped in a one to one relationship using a primary key i.e. 'student_id'.
-- 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.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;

-- Dumping structure for table hibernate_db.student_address
CREATE TABLE IF NOT EXISTS `student_address` (
  `student_id` bigint(100) NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `state` varchar(100) DEFAULT NULL,
  `country` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`student_id`),
  CONSTRAINT `FK_student_address_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Project Structure

This is the overall project structure for today's discussion. All required files are being explained in the rest part of this tutorial.


Pom.xml

This is a simple pom.xml containing dependencies to use in a hibernate one to one mapping relationship.
<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.hbnet</groupId>
 <artifactId>HibernateOneToOne</artifactId>
 <packaging>jar</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>HibernateOneToOne</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

This is a simple xml configuration file to contain code of hibernate configurations and settings. We have added all database related connections settings here along with a entry for each model class to let hibernate know about the relational mappings.
<?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.StudentAddress" />
 </session-factory>
</hibernate-configuration>


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

This is a simple java class containing code for 'Student' class, the fields of the class are being annotated by required annotations to let the class work as a mapping class to appropriate table in db. @Entity class denoted that the class is being mapped to a table with name specified in '@Table(name = "student")' annotation. @Id tells that the specified column is being used as a primary key in the table and @GeneratedValue makes the specified column a auto-increment field. @OneToOne(mappedBy = "student", cascade = CascadeType.ALL) tells that the particular column is being associated with 'Student' in a one to one relationship.
package com.beingjavaguys.domain;

/**
 * @author Nagesh Chauhan
 *
 */
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
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;

 @OneToOne(mappedBy = "student", cascade = CascadeType.ALL)
 private StudentAddress studentAddress;
 
 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 StudentAddress getStudentAddress() {
  return studentAddress;
 }

 public void setStudentAddress(StudentAddress studentAddress) {
  this.studentAddress = studentAddress;
 }
}



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

@GenericGenerator tells that the column will have a foreign key relationship with student class's primary key column. @PrimaryKeyJoinColumn species the primary key column to be served to make a foreign key relationship with student table.
package com.beingjavaguys.domain;

/**
 * @author Nagesh Chauhan
 *
 */
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "student_address")
public class StudentAddress {

 @Id
 @Column(name = "student_id")
 @GeneratedValue(generator = "gen")
 @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name = "property", value = "student"))
 private long id;

 @Column(name = "address")
 private String address;

 @Column(name = "city")
 private String city;

 @Column(name = "state")
 private String state;

 @Column(name = "country")
 private String country;

 @OneToOne
 @PrimaryKeyJoinColumn
 private Student student;
 
 public StudentAddress(){
  
 }

 public StudentAddress(String address, String city, String state,
   String country) {
  this.address = address;
  this.city = city;
  this.state = state;
  this.country = country;
 }

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 public Student getStudent() {
  return student;
 }

 public void setStudent(Student student) {
  this.student = student;
 }

}



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

This is another simple java class used to get a SessionFactory instance, to get a session object from.
package com.beingjavaguys.hbnet;

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;
    }
}



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

This is the main class where actual implementation will be made to demonstrate the undergoing functionality.
package com.beingjavaguys.hbnet;

/**
 * @author Nagesh Chauhan
 *
 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.beingjavaguys.domain.Student;
import com.beingjavaguys.domain.StudentAddress;

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" );
        StudentAddress studentAddress = new StudentAddress("g-147, sec-44", "new delhi", "new delhi", "india");
        
        student.setStudentAddress(studentAddress);
        studentAddress.setStudent(student);
        
        session.save(student);
        
        session.getTransaction().commit();
        session.close();
    }
}



Output




Table structure after implementation





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








Thanks for reading !
Being Java Guys Team

Download "Hibernate One to One Mapping Example Project" from "SkyDrive"





2 comments:

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft