Hibernate one-to-one unidirectional mapping using annotation

Hi friends,

Here i’m gonna tell you something about Hibernate mapping. I’m not exploring the core of hibernate Object Relational Mapping (ORM) tool. Let’s me come to the point.

I’m giving you an example of student and address. Since the relation is one to one, each student has exactly one address.

The DAO class looks like this, DAO.java.

package hba.dao;

import hba.util.HibernateUtil;
import org.hibernate.FlushMode;
import org.hibernate.Session;

public class DAO {

    private static final ThreadLocal THREAD = new ThreadLocal();

    protected DAO() {
    }

    public static Session getSession() {
        Session session = (Session) DAO.THREAD.get();
        if (session == null) {
            session = HibernateUtil.getSessionFactory().openSession();
            DAO.THREAD.set(session);
            getSession().setFlushMode(FlushMode.COMMIT);
        }
        return session;
    }

    protected static void begin() {
        getSession().beginTransaction();
    }

    protected static void commit() {
        getSession().getTransaction().commit();
    }

    protected static void rollback() {
        getSession().getTransaction().rollback();
        getSession().close();
        DAO.THREAD.set(null);
    }

    protected static void flush() {
        getSession().flush();
    }

    protected static void close() {
        getSession().close();
        DAO.THREAD.set(null);
    }
}

The hibernate configuration file, hibernate.cfb.xml.

<?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.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hba</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password1.</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="hba.pojo.o2o_u_student"/>
        <mapping class="hba.pojo.o2o_u_address"/>
    </session-factory>
</hibernate-configuration>

Here’s the student POJO, o2o_u_student.java.

package hba.pojo;

import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT", catalog = "hba")
public class o2o_u_student implements Serializable {

    private long std_id;
    private String std_name;
    private o2o_u_address std_address;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "STD_ADD_ID")
    public o2o_u_address getStd_address() {
        return std_address;
    }

    public void setStd_address(o2o_u_address std_address) {
        this.std_address = std_address;
    }

    @Id
    @GeneratedValue
    @Column(name = "STD_ID")
    public long getStd_id() {
        return std_id;
    }

    public void setStd_id(long std_id) {
        this.std_id = std_id;
    }

    @Column(name = "STD_NAME", length = 20, nullable = false)
    public String getStd_name() {
        return std_name;
    }

    public void setStd_name(String std_name) {
        this.std_name = std_name;
    }
}

Download Student POJO

Here’s the address POJO, o2o_u_address.java.

package hba.pojo;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "ADDRESS", catalog = "hba")
public class o2o_u_address implements Serializable {

    private long add_id;
    private String add_address;

    @Column(name = "ADD_ADDRESS", length = 50, nullable = false)
    public String getAdd_address() {
        return add_address;
    }

    public void setAdd_address(String add_address) {
        this.add_address = add_address;
    }

    @Id
    @Column(name = "ADD_ID")
    public long getAdd_id() {
        return add_id;
    }

    public void setAdd_id(long add_id) {
        this.add_id = add_id;
    }
}

Download address POJO

Finally, here’s the save() method.

public class o2o_u_std_add extends DAO {
public void save() {
        try {
            begin();
            o2o_u_student student = new o2o_u_student();
            o2o_u_address address = new o2o_u_address();
            address.setAdd_id(2);
            address.setAdd_address("Sydney Place, Washington, DC 20521-4150");
            student.setStd_name("deepesh");
            student.setStd_address(address);
            getSession().save(student);
            commit();
        } catch (Exception e) {
            rollback();
            System.out.println("Exception :" + e.getMessage() + "Cause :" + e.getCause());
        } finally {
            flush();
            close();
        }
    }

public static void main(String[] args) throws Exception {
        new o2o_u_std_add().save();
    }
}

Download save() method.

The output of the above save() method will be

Hibernate: select o2o_u_addr_.ADD_ID, o2o_u_addr_.ADD_ADDRESS as ADD2_1_ from hba.ADDRESS o2o_u_addr_ where o2o_u_addr_.ADD_ID=?
Hibernate: insert into hba.STUDENT (STD_ADD_ID, STD_NAME) values (?, ?)

Thank You.

Published by

Deepesh Darshan K R

I am Me. In all the world, there is no one else exactly like me. Everything that comes out of me is authentically mine, because I alone chose it. I own everything about me: my body, my feelings, my mouth, my voice, all my actions, whether they be to others or myself. I own my fantasies, my dreams, my hopes, my fears. I own my triumphs and successes, all my failures and mistakes. Because I own all of me, I can become intimately acquainted with me. By so doing, I can love me and be friendly with all my parts. I know there are aspects about myself that puzzle me, and other aspects that I do not know -- but as long as I am friendly and loving to myself, I can courageously and hopefully look for solutions to the puzzles and ways to find out more about me. However I look and sound, whatever I say and do, and whatever I think and feel at a given moment in time is authentically me. If later some parts of how I looked, sounded, thought, and felt turn out to be unfitting, I can discard that which is unfitting, keep the rest, and invent something new for that which I discarded. I can see, hear, feel, think, say, and do. I have the tools to survive, to be close to others, to be productive, and to make sense and order out of the world of people and things outside of me. I own me, and therefore, I can engineer me. I am me, and . . . . . . . . . . I am Okay. Haha.. Let it go.. I am a software engineer working in a MNC here at Kochi itself, specialized on J2EE platform, dribbling with frameworks like struts, hibernate etc.

7 thoughts on “Hibernate one-to-one unidirectional mapping using annotation”

  1. It is truly a nice and helpful piece of info. I am happy that you shared this helpful info with us. Please stay us informed like this. Thanks for sharing.

  2. I am truly pleased to glance at this webpage posts which carries tons of valuable data,
    thanks for providing such information.

Leave a comment