View RSS Feed

Spring Framework

Configuring a Hibernate SessionFactory in Spring

Rate this Entry
by , 11-27-2011 at 10:11 PM (7338 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:
package com.acme.springexamples.car.dao.config;
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.core.io.Resource; 
import org.springframework.orm.hibernate3.HibernateTemplate; 
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

@Configuration 
@ImportResource("classpath:hibernate-data-access.xml") 
public class CarHibernateConfig extends CarBaseConfig {
   @Value("hibernate.cfg.xml") 
    private Resource hibernateConfigResource;
    Resource hibernateConfigResource() { 
    return hibernateConfigResource;
}
// Local Session Factory for getting hibernate connections 
@Bean 
     LocalSessionFactoryBean sessionFactory() {
     LocalSessionFactoryBean sb = new LocalSessionFactoryBean(); 
     sb.setDataSource(dataSource()); 
     sb.setConfigLocation(hibernateConfigResource()); 
     return sb;
}

// Hibernate Template 
@Bean 
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 hbm2ddl.auto 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 del.icio.us Submit "Configuring a Hibernate SessionFactory in Spring" to StumbleUpon Submit "Configuring a Hibernate SessionFactory in Spring" to Google

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

Comments