spring事务问题求解

faith.huan 2014-09-08 01:38:02
代码如下 DataDao:
public class DataDao {

public void getMkmDetail(){
persistentDetail();
}

@Transactional
public void persistentDetail(){
//获取current session
System.out.println(hibernateUtil.getSession("current"));
}
}

调用方法及结果:
调用方法一:
public class DataLoader {
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
DataDao dd = (DataDao) ctx.getBean("dataDao");
dd.persistentDetail();
}

结果:可以打印session对象
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@1fbb60ad updates=org.hibernate.engine.spi.ExecutableList@46c80e21 deletions=org.hibernate.engine.spi.ExecutableList@7817bcd4 orphanRemovals=org.hibernate.engine.spi.ExecutableList@5e6e3fe4 collectionCreations=org.hibernate.engine.spi.ExecutableList@1824c22b collectionRemovals=org.hibernate.engine.spi.ExecutableList@1547a16f collectionUpdates=org.hibernate.engine.spi.ExecutableList@11b78953 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@2898b13b unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

调用方法一:
public class DataLoader {
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
DataDao dd = (DataDao) ctx.getBean("dataDao");
dd.getMkmDetail();
}

结果:Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread


求解 为什么直接调用可以,用方法间接调用就不行了

...全文
197 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
JavaPrimary 2014-09-09
  • 打赏
  • 举报
回复
楼主应该去查查@Transactional的作用。认识一下事物的开启和回滚
sinat_19250161 2014-09-09
  • 打赏
  • 举报
回复
在getMkmDetail方法上加上@Transactional注解试试
zycgod 2014-09-09
  • 打赏
  • 举报
回复
你getMkmDetail方法是不带事物的,调用带事物的persistentDetail方法时,由于采用了默认的事物传播机制,spring内部认为getMkmDetail已经开启了事物(包含了session的创建),所以在persistentDetail调用获得当前session的时候,会出现上述异常。在getMkmDetail方法上加上@Transactional注解应该就可以了。

67,550

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧