Java JPA与JTA事务-获取JDBC连接
这是我的班级:Java JPA与JTA事务-获取JDBC连接,java,jpa,transactions,entitymanager,jta,Java,Jpa,Transactions,Entitymanager,Jta,这是我的班级: @Stateless public class MyClass { @Inject UserTransaction tx; @PersistenceContext EntityManager em; public void myMethod() throws Exception { try { // ... tx.begin(); updateTa
@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连接?您可以从EntityManager中获取所述连接您可以从EntityManager中获取所述连接我正在使用JPA Hibernate。尝试此操作时,我遇到以下异常:javax.persistence.PersistenceException:Hibernate无法打开接口java.sql.Connection。我正在使用JPA Hibernate。尝试此操作时,我遇到以下异常:javax.persistence.PersistenceException:Hibernate无法打开接口java.sql.Connection。