【问题标题】:spring hibernate transaction could not commit春季休眠事务无法提交
【发布时间】:2013-05-04 19:54:11
【问题描述】:

我在春天写了 dao,就像我以前在 struts 中写的一样,有些人是这样认为的

@Autowired
    private SessionFactory sessionFactory;
    Session session=null;
    Transaction tx=null;
   List<Login> users= null;
    try{
        session=sessionFactory.getCurrentSession();
        tx=session.beginTransaction();
        users=session.createQuery("from Login").list();
        tx.commit();
    }catch(Exception e){System.out.println("commit exception:"+e);
        try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);} 
    }finally{if(session!=null && session.isOpen()){session.close();}}

但我收到此错误:

抛出异常[请求处理失败;嵌套异常是 org.springframework.transaction.TransactionSystemException:不能 提交休眠事务;嵌套异常是 org.hibernate.TransactionException:事务未成功 开始] 根本原因 org.hibernate.TransactionException: 交易未成功开始

谁能帮帮我。

如果我这样写,

try{
            users=sessionFactory.getCurrentSession().createQuery("from Login").list();
        }catch(Exception e){System.out.println("commit exception:"+e);

它工作正常,但它安全吗?

感谢和问候

【问题讨论】:

  • 你为什么要启动、提交和回滚事务,而不是让 Spring 使用 AOP 来做呢?我的猜测是您也在使用 Spring AOP 进行此操作,并且程序化事务处理正在干扰 Spring 自己的事务处理。
  • 是的,我在服务中使用了@transactional。那么这是最好的方法吗?

标签: spring hibernate spring-mvc transactions


【解决方案1】:

您正在使用 @Transactional,让 Spring 为您启动、提交和回滚事务,并以声明方式处理您的事务。这样做的全部意义在于不必在代码中启动、提交和回滚事务。所以方法实现应该很简单

return (List<Login>) sessionFactory.getCurrentSession().createQuery("from Login").list();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 2018-05-06
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多