gpt4 book ai didi

spring - 将服务类标记为事务性时 DAO 中出现 "No Session found for current thread"错误

转载 作者:行者123 更新时间:2023-12-01 12:53:39 24 4
gpt4 key购买 nike

使用 Hibernate 4 和 Spring 3.1。只是开始使用它,所以我可能缺乏理解。我在 Service 类中有一个方法,它调用 DAO 类中的一个方法来使用 Hibernate 检索一些数据。我用 @Transactional 注释 Service 方法,但在 DAO 方法中调用 getCurrentSession 时出错。如果我也使用 @Transactional 注释 DAO 方法,那么数据将被成功检索。我不明白为什么 - 我认为 Service 方法上的 @Transactional 注释会创建一个 Hibernate session ,将其绑定(bind)到线程,并且当调用 getCurrentSession 时该 session 将在 DAO 类中返回。谁能解释为什么会这样,或者我做错了什么,谢谢?

根上下文.xml:

<tx:annotation-driven transaction-manager="transactionManager"/>

服务类:

public class BlahServiceImpl implements BlahService {

@Transactional
public Blah GetMostRecentBlah() {
BlahDAO blahDAO = DAOFactory.GetBlahDAO();
return blahDAO.GetMostRecentBlah();
}
}

DAO 类:

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public Blah GetMostRecentBlah() {
return (Blah)sessionFactory.getCurrentSession().createQuery("from Blah where blahID = (select max(blahID) from Blah)").uniqueResult();
}

错误:

org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1039)
com.blah.blah.DAO.BlahDAOImpl.GetMostRecentBlah(BlahDAOImpl.java:18)

就像我说的,如果我用@Transactioanl(以及 Service 方法)注释 DAO 函数,这会起作用,但我不明白为什么。

最佳答案

有两个可能的原因。

1) 您的服务 bean 在一个单独的 ApplicationContext 中,它没有启用注解驱动的事务。

2) 您正在获取对服务实例的引用,该实例是原始实例而不是代理实例,因此是事务性实例。

要确定哪个是您的问题,或者确定它是否是其他问题,请显示导致创建服务 bean 的上下文文件,并显示您获取服务实例的代码。

关于spring - 将服务类标记为事务性时 DAO 中出现 "No Session found for current thread"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10807754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com