Hibernate kickstart

Jasper 4

A quick’n dirty tutorial-by-example for Hibernate:
(Using one table, an Oracle9+ database and Hibernate2)

1) download the Hibernate distribution

2) put these jarfiles in /WEB-INF/lib:

hibernate2.jar (hibernate core)
cglib-full-2.0.2.jar (runtime class-enhancing)
dom4j-1.4.jar (xml reading)
ehcache-0.9.jar (objectcache)
c3p0-0.8.4.5.jar (connectionpool)
jta.jar (transactions)

3) put this xml-file in your classpath (as /WEB-INF/classes/hibernate.cfg.xml):

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
	<session-factory>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@yourDBserver:port:name</property>
        <property name="connection.username">uid</property>
        <property name="connection.password">pass</property>

        <property name="show_sql">true</property>
        <property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property>

        <property name="c3p0.min_size">5</property>
        <property name="c3p0.max_size">20</property>
        <property name="c3p0.timeout">1800</property>
        <property name="c3p0.max_statements">50</property>

        <mapping resource="nl/amis/bookreviewstruts/bean/Review.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

4) Assuming this table:

TABLE BR_REVIEW (
    REVIEWID NUMBER NOT NULL,
    BOOKTITLE VARCHAR2 (255) NOT NULL,
    ISBN VARCHAR2 (100) NOT NULL,
    AUTHORS VARCHAR2 (255),
    PUBLISHER VARCHAR2 (100),
    REVIEWTITLE VARCHAR2 (255),
    REVIEWERS VARCHAR2 (255),
    APPRECIATION NUMBER
)

and a javabean like this:

public class Review
{
    private long reviewId;
    [..]
    public long getReviewId() { return this.reviewId;}
    public void setReviewId(long reviewId) { this.reviewId = reviewId;}
    [..]
}

create nl/amis/bookreviewstruts/bean/Review.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
    <class name="nl.amis.bookreviewstruts.bean.Review" table="BR_REVIEW">
        <id name="reviewId" unsaved-value="-1">
            <generator class="native"/>
        </id>
        <property name="bookTitle" not-null="true"/>
        [..]
    </class>
</hibernate-mapping>

5) Create the HibernateUtil class:

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HibernateUtil {
    private static Log log = LogFactory.getLog(HibernateUtil.class);
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
}

6) That’s it! Now for example query for all results:

    Session session = HibernateUtil.currentSession();
    List allReviews = session.find("from Review");
    HibernateUtil.closeSession();

More about querying and manipulating data can be found here, here, here or here

4 thoughts on “Hibernate kickstart

  1. I am a database professional and was responsible for migrating mysql database to oracle.
    I also had to demonstrate that application is working with migrated database.
    That’s it. I didn’t have the time and skills to learn hibernate.

    I needed exactly the kind of info as given here.

    Thank you very much for helping me complete my task.

Comments are closed.

Next Post

Formatting HTML forms part II

Facebook0TwitterLinkedinAfter my post on HTML forms yesterday I was fooling around with the fieldset and label tags. Both seem quite usefull! But Internet Explorer is really quite bad at rendering the fieldset. My 4-year old daughter does a better job of coloring inside the lines Mozilla Firefox is much better […]