Reputation: 670
The LocalSessionFactoryBean that comes with Spring ORM Hibernate 4 allowed for injecting a CacheRegionFactory through standard dependency injection for the cacheRegionFactory property.
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
Upvotes: 4
Views: 1429
Reputation: 2136
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();
}
}
Upvotes: 1
Reputation: 21
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();
}
Upvotes: 2
Reputation: 1642
Use the hibernate.cache.region.factory_class
property. Example usage:
<property name="hibernate.cache.region.factory_class"
value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
More info here: http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#caching-config-provider
Upvotes: -1