【问题标题】:JPA EntityManagerFactoryJPA EntityManagerFactory
【发布时间】:2012-10-20 11:21:16
【问题描述】:

我在我的项目中使用 jpa。但我必须调用所有方法并连接到数据库。我想用 entitymanagerfactory 和其他想要使用的方法连接一次数据库。我制作了静态 entitymanagerfactory 和 entitymanager,因此我接受了一个错误,即事务处于活动状态。

如何与 jpa 公开连接?

【问题讨论】:

  • 使用 JTA 代替本地资源。

标签: jpa hibernate-entitymanager


【解决方案1】:

我怀疑以后还会有其他问题,我建议您关注this tutorial,它展示了如何制作 Java SE JPA 应用程序。更完整的基础教程here 非常关注 Sun 自己的工具集和组件,但底层基础知识和示例代码可能会对您有所帮助。

总之,开头是这样的:

public static void main(String[] args) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnitName");
    EntityManager em = emf.createEntityManager();

    // let's start a transaction, everything we do from here on can be either
    // committed or rolled back, ensuring the integrity of our data
    em.getTransaction().begin();
    // update the database here


    // okay, done
    em.getTransaction().commit();

    // and housekeeping, close em an emf
    em.close();
    emf.close();

}

如您所见,em 和 emf 都不必是静态的。如果您(您应该)将项目细分为对象,您可以将em 传递给这些将使用它与数据库交互的对象。此外,您不限于只有一个跨越应用程序整个生命周期的大事务,您可以有多个连续的。

【讨论】:

  • 好的。我用 if(!em.gettransaction.isActive()) 解决了。感谢您的帮助
猜你喜欢
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2012-03-08
  • 2013-07-28
  • 2018-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多