jax*_*jax 12 spring hibernate spring-boot
我试图访问Hibernate会话工厂,但在提到的行中收到以下错误.
No CurrentSessionContext configured!
Run Code Online (Sandbox Code Playgroud)
码
@Service
@Transactional
public class GenericSearchImpl implements GenericSearch {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Override
@SuppressWarnings("unchecked")
public <T> List<T> search(final Class<T> type, final String[] criteriaList, final int page, final int perPage) {
Session session = getSession();
...
}
public Session getSession() {
final HibernateEntityManagerFactory emFactory = (HibernateEntityManagerFactory) entityManagerFactory;
final SessionFactory sessionFactory = emFactory.getSessionFactory();
return sessionFactory.getCurrentSession(); //ERROR No CurrentSessionContext configured!
//This worked but I understand it to be BAD as spring should be managing open sessions.
// try {
// return sessionFactory.getCurrentSession();
// } catch (Exception e) {
// return sessionFactory.openSession();
// }
}
...
}
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?
Ana*_*and 11
在属性文件中,
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
Run Code Online (Sandbox Code Playgroud)
在配置类中
@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以自动装配
@Autowired
private SessionFactory sessionFactory;
Run Code Online (Sandbox Code Playgroud)
我们这样做是因为Spring启动不会自动配置hibernate sessinoFactory.
更新:从Spring 4.3.12和Hibernate 5.2开始,上面的Hibernate API解决方案被折旧,转而使用通用JPA API解决方案EntityManagerFactory.
Session session = entityManager.unwrap(Session.class);
Run Code Online (Sandbox Code Playgroud)
这是一些详细的示例文档,其中包含有关EntityManagerFactory的示例.
小智 6
您可以使用 entityManagerFactory 解包方法而不是 HibernateJpaSessionFactoryBean 访问 SessionFactory
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Run Code Online (Sandbox Code Playgroud)
HibernateJpaSessionFactoryBean 在 Spring Boot 1.5.8 中被弃用
| 归档时间: |
|
| 查看次数: |
12606 次 |
| 最近记录: |