
前提
在yml或properties文件中配置数据库与数据库连接池
Hibernate配置
几种方式:
方式一:
@Configuration
public class HibernateConfig { @Bean
public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf){
return emf.unwrap(SessionFactory.class);
} }
方式二:
@Autowired
private EntityManagerFactory entityManagerFactory; @Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
方式三:
在属性配置文件中配置(可有可无)
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
方式四:
在属性配置文件中配置(可有可无)
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
调用
@Autowired
private SessionFactory sessionFactory;