方式一:
@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;
from:https://www.cnblogs.com/soul-wonder/p/9052471.html
备注:以上是别人的配置,我测试过,好像有些有点问题。下面是我根据别人的描述,自己的配置,亲测有效
@Repository("baseDao")
@Transactional
public class BaseDaoImpl implements BaseDao {
@PersistenceContext
@Autowired
private EntityManager entityManagerFactory;
@Bean
public Session getCurrentSession() {
return this.entityManagerFactory.unwrap(Session.class);
}
public <T> Serializable save(T obj) {
return this.getCurrentSession().save(obj);
}
.....
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/数据库名
username: 用户名
password: 秘密
driver-class-name: com.mysql.jdbc.Driver
jpa:
open-in-view: true
#database-platform: org.hibernate.dialect.MySQLDialect
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
activiti:
check-process-definitions: false
db-identity-used: false