Hibernate sessionfactory, as the name suggests, is something that can open and manage hibernate sessions with database. Hibernate encapsulates everything that a developer (appropriately a developer who knew Java/.Net and Sql) used to do to interact with database. It offers many controllable parameters in this interaction. These parameters can be connection attributes, number of connections, logging parameters etc.

There are two primary ways to configure these parameters:

Programmatic Configuration: In this the configuration parameters are kept in code. The disadvantage is – whenever you want to change any parameter, you will have to change, compile and deploy the code again.

Configuration xml: Usually it is done using hibernate.cfg.xml, but one can think of using environment specific property files, so that you don’t have to change the properties when application moves from one environment to other during development stage.

Programmatic Configuration Example:
As stated earlier, in this method the configuration is done in code. We can use Configuration object to create collection of properties. Further java.util.Properties object can be passed to Configuration object. This configuration can be given to create sessionfactory.

Configuration cfg = new Configuration()
.addClass(Cat.class)
.setProperty("hibernate.dialect",
  "org.hibernate.dialect.Oracle9Dialect")
.setProperty("hibernate.connection.datasource",
      "java:comp/env/jdbc/oracletestdb");

Configuration xml Example:
Here we write the configuration parameters in a xml file and give this as input while building the xml.

Sample hibernate.cfg.xml:

<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration
PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory>
<property name=”dialect”>org.hibernate.dialect.Oracle9Dialect</property>
<property name=”connection.driver_class”> oracle.jdbc.driver.OracleDriver </property>
<property name=”connection.url”>jdbc:oracle:thin:@server:port:DB</property>
<property name=”connection.username”>UserID</property>
<property name=”connection.password”>Password</property>

<property name=”hibernate.show_sql”>true</property>
<property name=”hibernate.hbm2ddl.auto”>create-drop/update</property>

<mapping resource=”Cat.hbm.xml”/>

</session-factory>
</hibernate-configuration>

Discussing Different Configuration Parameters:

Following are the important set parameters being configured in any hibernate.cfg.xml

1. Database Connection:
Database connection can be obtained using connection attributes (user/password, driver and connection url) or making JNDI lookup. Later is better because you can have same JNDI name configured on different application servers which will point the connection to required database, e.g. for system testing you different db, you can use configuration file without any change, and make the JNDI configuration to handle the connection to your selected DB.

2. Transaction Management:
Which transaction management mechanism you want to use can be specified here. If you don’t specify anything here, that means hibernate needs to do nothing to begin and end transactions and you are taking care of it in code. Other option is defining here to use transaction manager.

<property name=”transaction.factory_class”>
org.hibernate.transaction.JTATransactionFactory
</property>
<property name=”jta.UserTransaction”>java:comp/UserTransaction</property>

3. Caching:
Hibernate caches data at transaction level in a session. But if you want to cache the data one level higher i.e. session factory level then it can be specified using second level cache. Call to implement second level cache should be taken after considering all aspects of it. Clustering plays important role here. Also second level cache requires cache provider name.  Select appropriate cache provider considering whether memory or disc to store, cluster safety required and whether you want to cache query. To disable cache it will be following configuration:

<property name=”hibernate.cache.use_second_level_cache”>false</property>
<property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

4. Automatic Session Context Management:
This goes well with JTA transaction management. By defining this attribute we can make sessionFactory.getCurrentSession call to retrieve session associated with current transaction. Otherwise it will require opening a session. Opening too many sessions degrades performance.

<property name=”current_session_context_class”>thread</property>
<property name=”hibernate.jdbc.use_streams_for_binary”>true</property>

5. Batch Size:
This property manages the number of database operations (insert/update/delete primarily), before the commit is executed. It is using the batch update mode of database. One definitely needs to set auto commit of database to false before using batch update mode.

<property name=”hibernate.jdbc.batch_size”>20</property>

6. Object Mapping:
This is final core part of mapping xml where the object relation mappings are connected to session factory. Hibernate verifies all these mappings while creating instance of session factory using this configuration.

<mapping resource=”Cat.hbm.xml”/>

7. Creating Session Factory

When hibernate.cfg.xml in classpath, following simple line will do.

SessionFactory sf = new Configuration().configure().buildSessionFactory();

If your configuration file is named at differently and is at different location than direct class path (usually /classes directory of application) then following code should be used.

SessionFactory sf = new Configuration().configure(“MyHibernate.cfg.xml”).buildSessionFactory();

Singleton SessionFactory:

It is always recommended that there is one session factory per database, per JVM. Having multiple instances of session factory can lead to performance problems as well as abnormal behavior of transactions.

Creation of Hibernate SessionFactory with Spring:

Spring provides support for hibernate through following classes. When integrated with Spring, we are using hibernate through Spring container. It makes many services provided by Spring container available to the application. Further, spring has good support for unit testing of classes using hibernate.

org.springframework.orm.hibernate3.support.HibernateDaoSupport,
org.springframework.jdbc.datasource.DriverManagerDataSource,
org.springframework.orm.hibernate3.LocalSessionFactoryBean,
org.springframework.orm.hibernate3.HibernateTransactionManager

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS