ITPub博客

首页 > 数据库 > 数据库开发技术 > 处理Hibernate “save is not valid without active transaction”异常

处理Hibernate “save is not valid without active transaction”异常

原创 数据库开发技术 作者:wolaiye320 时间:2009-07-05 23:16:53 0 删除 编辑

原本代码:

public Session getCurrentSession() {
return HibernateUtil.getSessionFactory().getCurrentSession();
}

public void createUser(User user) {
getCurrentSession().beginTransaction();
getCurrentSession().save(user);
getCurrentSession().getTransaction().commit();
}

提示错误信息:

严重: Servlet.service() for servlet action threw exception
org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:297)
at $Proxy12.save(Unknown Source)
at com.sg.blog.dao.impl.UserDaoImpl.createUser(UserDaoImpl.java:15)
at com.sg.blog.bean.impl.UserBeanImpl.createUser(UserBeanImpl.java:13)
at com.sg.blog.web.acton.RegistAction.execute(RegistAction.java:50)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)

后来方式代码 getCurrentSession().beginTransaction();
getCurrentSession().save(user);
getCurrentSession().getTransaction().commit();
的getCurrentSession()返回的session不是同一个对象。因此 getCurrentSession().save(user);就提示“save is not valid without active transaction”错误。 将代码改成使用同一个session即可解决问题。代码如下:
public void createUser(User user) {
session = getCurrentSession();
Transaction tran = session.beginTransaction();
session.save(user);
tran.commit();
}

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1700919/viewspace-1023803/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 草稿
请登录后发表评论 登录
全部评论

注册时间:2008-06-23

  • 博文量
    19
  • 访问量
    827670