View RSS Feed

Spring Framework

Configuring a Hibernate SessionFactory in Spring

Rate this Entry
by , 11-27-2011 at 11:11 PM (7895 Views)
In an earlier post, I showed you how to integrate Hibernate with Spring using the annotation oriented persistence. For those still interested in the standard way I outline how you can accomplish that below. The key to the standard way is to use a Hibernate org.hibernate.SessionFactory for all access to the database through the domain objects. The Java configuration for the SessionFactory is shown below.

Java Code:
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource; 
import org.springframework.orm.hibernate3.HibernateTemplate; 
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

public class CarHibernateConfig extends CarBaseConfig {
    private Resource hibernateConfigResource;
    Resource hibernateConfigResource() { 
    return hibernateConfigResource;
// Local Session Factory for getting hibernate connections 
     LocalSessionFactoryBean sessionFactory() {
     LocalSessionFactoryBean sb = new LocalSessionFactoryBean(); 
     return sb;

// Hibernate Template 
public HibernateTemplate hibernateTemplate() {
    return new HibernateTemplate(sessionFactory().getObject());
I am assuming here that you have already created the table in a database schema to store objects. If you have not, please do this always before trying to configure hibernate in Spring. Fortunately with Hibernate, you donít need to design the tables by yourself if the property is set to update, Hibernate will update the database schema and create the tables when necessary. This only applies to development. Once you get into production, make sure that this option is turned off.

Submit "Configuring a Hibernate SessionFactory in Spring" to Facebook Submit "Configuring a Hibernate SessionFactory in Spring" to Digg Submit "Configuring a Hibernate SessionFactory in Spring" to Submit "Configuring a Hibernate SessionFactory in Spring" to StumbleUpon Submit "Configuring a Hibernate SessionFactory in Spring" to Google

Tags: hibernate Add / Edit Tags
Hibernate , Configuration , Spring 3