Does anyone know how to get a handle the Hibernate SessionFactory that is created by Spring Boot?
Spring provides a much, much nicer way of configuring a Hibernate SessionFactory - the LocalSessionFactoryBean (see docs for example usage). LocalSessionFactoryBean produces a SessionFactory object, which you can inject as a property into your DAO beans.
The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.
You can accomplish this with:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory is an JPA EntityManagerFactory
.
package net.andreaskluth.hibernatesample; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class SomeService { private SessionFactory hibernateFactory; @Autowired public SomeService(EntityManagerFactory factory) { if(factory.unwrap(SessionFactory.class) == null){ throw new NullPointerException("factory is not a hibernate factory"); } this.hibernateFactory = factory.unwrap(SessionFactory.class); } }
The simplest and least verbose way to autowire your Hibernate SessionFactory is:
This is the solution for Spring Boot 1.x with Hibernate 4:
application.properties:
spring.jpa.properties.hibernate.current_session_context_class= org.springframework.orm.hibernate4.SpringSessionContext
Configuration class:
@Bean public HibernateJpaSessionFactoryBean sessionFactory() { return new HibernateJpaSessionFactoryBean(); }
Then you can autowire the SessionFactory
in your services as usual:
@Autowired private SessionFactory sessionFactory;
As of Spring Boot 1.5 with Hibernate 5, this is now the preferred way:
application.properties:
spring.jpa.properties.hibernate.current_session_context_class= org.springframework.orm.hibernate5.SpringSessionContext
Configuration class:
@EnableAutoConfiguration ... ... @Bean public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) { HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean(); fact.setEntityManagerFactory(emf); return fact; }
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