Hibernate one-to-many unidirectional mapping using annotation

Hi friends,

Welcome back to hibernate mapping..

Here, we can discuss more about hibernate one-to-many unidirectional mapping with an example. After reading this post, you will definitely get to know how to code a hibernate one-to-many unidirectional mapping program.

Now come to the point. One-to-many mapping means, one entity in parent table can have one or more children in child table. To be in detail, By querying parent, we will also get its children’s properties. Please note that this will only happen if the fetch type is EAGER. If it LAZY, we would have to explicitly query the children.

Why it is called unidirectional, because, we can get child details when we just query its parent, but will not happen vice versa, ie; we could not find out a parent by giving child details.

Here, we can talk over an one-to-many unidirectional mapping example. I use LAZY fetching over here.

if you want to recall one-to-one unidirectional and bidirectional mapping, just drive around and come back.

So, let’s start.

Here’s my DAO class, 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">password</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="hba.pojo.o2m_u_blog"/>
        <mapping class="hba.pojo.o2m_u_post"/>
    </session-factory>
</hibernate-configuration>

My parent POJO, o2m_u_blog.java.

package hba.pojo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
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.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

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

    private long blg_id;
    private String blg_name;
    private List<o2m_u_post> blg_posts = new ArrayList<o2m_u_post>();

    @Id
    @GeneratedValue
    @Column(name = "BLG_ID")
    public long getBlg_id() {
        return blg_id;
    }

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "BLOG_POST", joinColumns = {
        @JoinColumn(name = "BLG_ID")}, inverseJoinColumns = {
        @JoinColumn(name = "PST_ID")})
    public List<o2m_u_post> getBlg_posts() {
        return blg_posts;
    }

    @Column(name = "BLG_NAME", length = 20)
    public String getBlg_name() {
        return blg_name;
    }

    public void setBlg_id(long blg_id) {
        this.blg_id = blg_id;
    }

    public void setBlg_name(String blg_name) {
        this.blg_name = blg_name;
    }

    public void setBlg_posts(List<o2m_u_post> blg_posts) {
        this.blg_posts = blg_posts;
    }

    public o2m_u_blog(long blg_id) {
        this.blg_id = blg_id;
    }

    public o2m_u_blog() {
    }
}

The child POJO, o2m_u_post.java.

package hba.pojo;

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

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

    private long pst_id;
    private String pst_name;

    @Id
    @GeneratedValue
    @Column(name = "PST_ID")
    public long getPst_id() {
        return pst_id;
    }

    @Column(name = "PST_NAME", length = 20)
    public String getPst_name() {
        return pst_name;
    }

    public void setPst_id(long pst_id) {
        this.pst_id = pst_id;
    }

    public void setPst_name(String pst_name) {
        this.pst_name = pst_name;
    }

    public o2m_u_post(String pst_name) {
        this.pst_name = pst_name;
    }

    public o2m_u_post(long pst_id) {
        this.pst_id = pst_id;
    }

    public o2m_u_post() {
    }
}

This is my business class, o2m_u_blg_pst.java, in which I have written methods for saving and listing data.Here’s the save() method.

package hba.biz;

import hba.dao.DAO;
import hba.pojo.o2m_u_blog;
import hba.pojo.o2m_u_post;
import java.util.ArrayList;
import java.util.List;

public class o2m_u_blg_pst extends DAO {

    public void save() {
        try {
            begin();
            List<o2m_u_post> posts = new ArrayList<o2m_u_post>();
            o2m_u_blog blog = new o2m_u_blog();
            posts.add(new o2m_u_post("Struts 2"));
            posts.add(new o2m_u_post("Hibernate 3"));
            blog.setBlg_name("My Java");
            blog.setBlg_posts(posts);
            getSession().save(blog);
            commit();
        } catch (Exception e) {
            rollback();
            System.out.println("Exception : " + e.getMessage() + "Cause : " + e.getCause());
        } finally {
            flush();
            close();
        }
    }

    public static void main(String[] args) {
        try {
            new o2m_u_blg_pst().save();
        } catch (Exception e) {
            System.out.println("Exception in main." + e.getMessage());
        }
    }
}

Here, I’ve created two posts about “Struts 2” and “Hibernate 3” and put those posts under a blog “My Java”. Finally I’ve saved my blog. It will also be saving two posts and automatically creating a new join table with mappings between blog and posts.

This will be the output when I execute save() method.

Hibernate: insert into hba.BLOG (BLG_NAME) values (?)
Hibernate: insert into hba.POST (PST_NAME) values (?)
Hibernate: insert into hba.POST (PST_NAME) values (?)
Hibernate: insert into BLOG_POST (BLG_ID, PST_ID) values (?, ?)
Hibernate: insert into BLOG_POST (BLG_ID, PST_ID) values (?, ?)

This is how I am retrieving my data, the list() method.

package hba.biz;

import hba.dao.DAO;
import hba.pojo.o2m_u_blog;
import hba.pojo.o2m_u_post;
import java.util.ArrayList;
import java.util.List;

public class o2m_u_blg_pst extends DAO {

    public void list() {
        try {
            List<o2m_u_blog> blogs = getSession().createQuery("from o2m_u_blog").list();
            for (o2m_u_blog blog : blogs) {
                System.out.println("Blog Name: " + blog.getBlg_name());
                List<o2m_u_post> posts = blog.getBlg_posts();
                for (o2m_u_post post : posts) {
                    System.out.println("Post Name: " + post.getPst_name());
                }
            }
        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage() + "Cause : " + e.getCause());
        }
    }

    public static void main(String[] args) {
        try {
            new o2m_u_blg_pst().list();
        } catch (Exception e) {
            System.out.println("Exception in main." + e.getMessage());
        }
    }
}

This will be the output.

Hibernate: select o2m_u_blog0_.BLG_ID as BLG1_2_, o2m_u_blog0_.BLG_NAME as BLG2_2_ from hba.BLOG o2m_u_blog0_
Blog Name: My Java
Hibernate: select blg_posts0_.BLG_ID as BLG1_1_, blg_posts0_.PST_ID as PST2_1_, o2m_u_post1_.PST_ID as PST1_3_0_, o2m_u_post1_.PST_NAME as PST2_3_0_ from BLOG_POST blg_posts0_ left outer join hba.POST o2m_u_post1_ on blg_posts0_.PST_ID=o2m_u_post1_.PST_ID where blg_posts0_.BLG_ID=?
Post Name: Struts 2
Post Name: Hibernate 3

Thanks.