Searching...
Thursday, 15 August 2013

Hibernate One to One Mapping Simple Example Using Annotations

08:46

Here is one simple example to implement Hibernate One to One entity relationship using Hibernate Annotations. Let us consider Student and Student Mark list relationship. One student has only one Mark list.

Follow below steps to implement this association in Hibernate. In this example we used Java 1.7, Hibernate 3, Eclipse and MySQL .

image

1. Create a Java project and add Hibernate Libraries

image

2. Create Student Mark List entity (StudentMarkList.java)

package com.pretech;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "studentmarklist", catalog = "hibernateschema")
public class StudentMarkList {
    @Id  
    @Column(name="marklistnumber")
    private String marklistnumber;
    @Column(name="subject")  
    private String subject;
    @Column(name="grade")  
    private String grade;
   
    public String getNumber() {
        return marklistnumber;
    }
    public void setNumber(String number) {
        this.marklistnumber = number;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
}

3. Create Student entity (Student.java)

package com.pretech;
 
import java.io.*;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
 
@Entity
@Table(name = "student", catalog = "hibernateschema")
public class Student  {
    @Id
    @Column(name = "name", unique = true, nullable = false, length = 100)
    private String name;
 
    @Column(name = "standard", unique = true, nullable = false, length = 200)
    private String standard;
   
    @OneToOne  
    @JoinColumn(name="marklistnumber")
    private StudentMarkList studentMarkList;  
 
    public StudentMarkList getStudentMarkList() {
        return studentMarkList;
    }
 
    public void setStudentMarkList(StudentMarkList studentMarkList) {
        this.studentMarkList = studentMarkList;
    }
 
    public String getStandard() {
        return standard;
    }
 
    public void setStandard(String standard) {
        this.standard = standard;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String string) {
        name = string;
    }
 
    public String toString() {
        return name;
    }
}
 
Note:
@OneToOne annotation is used to create one to one relationship
@JoinColumn is used to indicate mapped column

4. Create Hibernate config file (hibernate.cfg.xml)

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="studentFactory">
            <property name="connection.driver_class">
                 com.mysql.jdbc.Driver
            </property>
        <property name="connection.url">
             jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
             root
        </property>
        <property name="connection.password">
            root
        </property>
            <property name="connection.pool_size">5</property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
             <property name="hbm2ddl.auto">update</property>
             <mapping class="com.pretech.Student"></mapping>
             <mapping class="com.pretech.StudentMarkList"></mapping>
    </session-factory>
</hibernate-configuration>

5. Create a Main program to save entities

package com.pretech;
 
import org.hibernate.*;
import org.hibernate.cfg.*;
 
public class StudentMain {
    private static SessionFactory sessionFactory;
 
    public static void main(String args[]) throws Exception {
 
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        Student student = new Student();
        student.setName("Santhosh1");
        student.setStandard("9th Standard1");
       
        StudentMarkList sm=new StudentMarkList();
        sm.setNumber("111");
        sm.setSubject("Science");
        sm.setGrade("A");
        student.setStudentMarkList(sm);
        session.save(sm);
        session.save(student);
        tx.commit();
        System.out.println("Updated to Student details table");
        if (session != null)
            session.close();
    }
}

6. Output

Console

Hibernate: insert into hibernateschema.studentmarklist (grade, subject, marklistnumber) values (?, ?, ?)
Hibernate: insert into hibernateschema.student (standard, marklistnumber, name) values (?, ?, ?)
Updated to Student details table

Table records


image

image

 

0 comments: