Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure sessionFactory with Spring, Hibernate and LocalSessionFactoryBuilder

I'm trying to create sessionFactory bean using spring 3.2 and hibernate 4. I used the following code for that. But the problem is buildSessionFactory() is deprecated and the buildSessionFactory(ServiceRegistry serviceRegistry) is suggested to use instead in javadoc. However, I'm not being able to understand what is ServiceRegistry and how to use buildSessionFactory(ServiceRegistry serviceRegistry).


@Configuration
public class AppConfig {

    ...


    @Bean
    public SessionFactory sessionFactory() {
    return new LocalSessionFactoryBuilder(dataSource())
        .scanPackages("com.mypackages")
        .addProperties(hibernateProperties())
        .buildSessionFactory();

    }
}
like image 282
TheKojuEffect Avatar asked Feb 11 '13 05:02

TheKojuEffect


1 Answers

ServiceRegistry interface is related to concept of services (that is new for Hibernate 4). Services are classes that provide Hibernate with various functionality and for which user can plug in alternate implementations. See this wiki page for details.

You are right that method buildSessionFactory() is deprecated in Hibernate's Configuration class in favor of method buildSessionFactory(ServiceRegistry serviceRegistry). In a pure Hibernate's environment (without Spring) it is supposed that you will initialize instance of ServiceRegistry in such a way:

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();
    configuration.configure();

    serviceRegistry = new ServiceRegistryBuilder()
             .applySettings(configuration.getProperties())
             .buildServiceRegistry();

    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

But by now the deprecated method buildSessionFactory() also does the same initialization of ServiceRegistry for you.

Spring's LocalSessionFactoryBuilder class is just the extension of Hibernate's Configuration class. But since all the specific work of Spring is done in overriden method LocalSessionFactoryBuilder.buildSessionFactory() you can't use method buildSessionFactory(ServiceRegistry serviceRegistry) in Spring's environment. Nothing much 'cause it's ok to use buildSessionFactory() that does exactly the same work. So let's just annotate the method in AppConfig with @SuppressWarnings("deprecation") and patiently wait for Spring to provide better integration with Hibernate 4.

like image 155
Artem Shafranov Avatar answered Sep 19 '22 08:09

Artem Shafranov