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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With