Wednesday, February 17, 2010

Configure Hibernate to Use A Datasource

I'm using Glassfish application server, on which (using its Console) I have created a JDBC datasource (JDBC Resource). I'd like configure the hibernate framework to use it. The resons:
  • Connection pooling (it's true that I could use the Hibernate's own connection pooling)
  • Portability: moving the application to another application server is easy, as long as they both provide a datasource with the same name (Hibernate dialect may still need to be changed appropriately).
hibernate.cfg.xml File
<?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 name="hibernate/sessionFactory">
        <property name="connection.datasource">jdbc/derbydb</property>
        <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="hbm2ddl.auto">create</property>
    
     <mapping resource="olcc/entity/Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


HibernateUtil.java File
private static SessionFactory buildSessionFactory() {
    return new Configuration().configure().buildSessionFactory();
}


The Application Code
Session session = HibernateUtil.getSessionFactory().getCurrentSession();

1 comment:

Felix said...

I was trying your example, but could'nt succeed. The reason is due to Personcollection class. Could you please upload the code for PersonCollection.

Thanks in advance.

Felix