The LocalSessionFactoryBean that comes with Spring ORM Hibernate 4 allowed for injecting a CacheRegionFactory through standard dependency injection for the cacheRegionFactory property.
" rel="nofollow">Hibernate 4 LocalSessionFactoryBean Javadoc
Now for the LocalSessionFactoryBean that ships with Spring ORM Hibernate 5 there is no such property anymore.
Hibernate 5 LocalSessionFactoryBean Javadoc
Being able to inject the region factory is very handy when finer control is needed over the cache configuration, especially when configuring Hibernate as second-level cache with Spring.
My use case is dynamically specifying members of a TCP/IP Hazelcast cluster based on my app configuration file. Hazelcast is used as second level cache.
How can I inject a Spring-managed cache region factory into a Hibernate 5 LocalSessionFactoryBean through Spring dependency injection? Suggestions for different approaches also welcome.
Hibernate version: 5.1.0, Spring/Spring ORM version: 4.2.5, Hazelcast version: 3.6.4
You can create your own session factory bean extending from LocalSessionFactoryBean and overriding the method buildSessionFactory to provide Hibernate with your own region factory via ServiceRegistryBuilder:
class MySessionFactoryBean extends LocalSessionFactoryBean {
private final RegionFactory regionFactory;
MySessionFactoryBean(RegionFactory regionFactory) {
this.regionFactory = regionFactory;
}
@Override
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
StandardServiceRegistryBuilder serviceRegistryBuilder = sfb.getStandardServiceRegistryBuilder();
serviceRegistryBuilder.addService(RegionFactory.class, regionFactory);
return sfb.buildSessionFactory();
}
This functionality has been recently restored, and the fix will be available Spring Framework 5.1 RC1.
Issue link to Spring Framework JIRA: https://jira.spring.io/browse/SPR-17043
The answer from Arthur will work, but there is also a slightly shorter variant:
public class MyLocalSessionFactoryBean extends LocalSessionFactoryBean {
private RegionFactory regionFactory;
@Required
public void setRegionFactory(RegionFactory regionFactory) {
this.regionFactory = regionFactory;
}
@Override
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
sfb.getProperties().put(AvailableSettings.CACHE_REGION_FACTORY, regionFactory);
return sfb.buildSessionFactory();
}
}
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