【发布时间】:2015-05-27 09:05:13
【问题描述】:
我正在尝试访问 Hibernate 会话工厂,但在提到的行出现以下错误。
No CurrentSessionContext configured!
代码
@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();
// }
}
...
}
知道为什么吗?
【问题讨论】:
-
JPA 不使用
CurrentSessionContext类。配置它应该可以解决您的问题。只需添加当前会话上下文的配置并让它指向org.springframework.orm.hibernate4.SpringSessionContext类。但是,您为什么要这样做?为什么不使用普通的 JPA? -
@M.Deinum 我这样做是为了支持一些使用 Hibernate Criteria 的遗留代码。它最终将转换为 JPA。应用程序的其余部分使用 spring-data-jpa,我只需要临时使用 Hibernate SessionFactory,直到它可以重写。像这样的混合方法会奏效吗?你能举一个在java config中将CurrentSessionContext配置为spring bean的例子吗?
-
this 是什么意思?
-
是的(因为这基本上是同一个问题,所以将这个问题标记为重复)。
-
stackoverflow.com/questions/18759978/…。请参考这里。向您展示如何做到这一点。
标签: spring hibernate spring-boot