【问题标题】:org.hibernate.TransactionException: nested transactions not supportedorg.hibernate.TransactionException:不支持嵌套事务
【发布时间】:2013-09-12 08:16:45
【问题描述】:

我正在尝试使用 Hibernate 和 JSF 完成一项小任务。

这是我的 sn-p 代码。应该检索标签列表的托管 bean 方法:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
public  List<WikiTag> getTags(){
    session.getTransaction().begin();
    Criteria crit = session.createCriteria(WikiTag.class);
    List<WikiTag> result = crit.list();     
    return result;
}

我了解我不能打开多个会话。但是,当我从 facelet 调用代码的 sn-p 时,我得到了

org.hibernate.TransactionException: nested transactions not supported

对此提出的任何启示都非常感谢。谢谢

【问题讨论】:

    标签: hibernate facelets


    【解决方案1】:

    您不能同时激活一个以上的事务(不是会话)(我正在写关于您的案例)。
    可能您的方法已经在交易中,您不需要创建新方法;删除 session.getTransaction().begin();.
    How to avoid nested transactions not supported error?

    顺便说一句,事务管理的正确伪代码是:

    tx = begin tx;
    try
    {
      do database operations;
      commit tx;
      tx = null;
    }
    finally
    {
      if(tx != null)
      {
        rollback tx;
      }
    }
    

    【讨论】:

    • 我只打开了一笔交易。当我删除该行 session.getTransaction().begin(); 时,我得到 org.hibernate.HibernateException: createCriteria is not valid without active transaction
    • 您是否尝试过开始/提交/回滚最佳实践?你的代码不正确,因为你从来没有关闭你开始的事务(重写和重试)
    • 我试过了,先生。但我遇到了第三个例外org.hibernate.SessionException: Session is closed!
    【解决方案2】:

    首先,在 getter setter 中访问数据库是错误的。渲染页面期间多次调用getTags 方法。您不能在操作方法中进行事务性数据库连接..

    其次,在 JSF 操作中访问数据库不是一个好习惯。您应该在通常称为 DAO 类的其他类中访问数据库。

    另见

    Database Communication in JSF/EJB

    DAO tutorial - the data layer

    【讨论】:

    • 谢谢先生。感谢您的宝贵时间。
    猜你喜欢
    • 2016-06-30
    • 2014-12-24
    • 1970-01-01
    • 2013-05-10
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多