【问题标题】:JPA with JTA transactions - get the JDBC connection带有 JTA 事务的 JPA - 获取 JDBC 连接
【发布时间】:2014-07-18 08:12:47
【问题描述】:

这是我的课:

@Stateless
public class MyClass {

    @Inject
    UserTransaction tx;

    @PersistenceContext
    EntityManager em;

    public void myMethod() throws Exception {
        try {
            // ...
            tx.begin();
            updateTable1();
            updateTable2();
            tx.commit();
        } catch(Exception ex) {
            tx.rollback();
            throw ex;
        }
    }

    private void updateTable1() {
        Query query = em.createNamedQuery(Table1.updateQuery);
        query.executeUpdate();
    }

    private void updateTable2() {
        Query query = em.createNamedQuery(Table2.updateQuery);
        query.executeUpdate();
    }
}

JTA 数据源在 persistence.xml 中定义。

这是我对这个类的理解:tx.begin() 从连接池中获取一个连接。此连接将由实体管理器在 updateTable1() 和 updateTable2() 中使用。 tx.commit() 在将更改提交到数据库后将连接返回到连接池。我说的对吗?

我是否可以在 myMethod() 中获取事务中使用的 JDBC 连接?

【问题讨论】:

    标签: java jpa transactions entitymanager jta


    【解决方案1】:

    您可以按照here 的描述从 EntityManager 获取连接

    【讨论】:

    • 我正在使用 JPA Hibernate。尝试此操作时,出现以下异常: javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多