我在我的项目中使用jpa。但是我必须调用所有的方法并连接到数据库。我想用entitymanagerfactory和其他方法连接一次数据库。我设置了静态的entitymanager工厂和entitymanager,因此ı会产生一个错误,即事务是活动的。
如何实现与jpa的公开连接?
发布于 2012-10-20 19:49:41
因为我怀疑稍后还会有其他问题,所以我建议您参考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传递给这些对象,这些对象将使用它与数据库进行交互。而且,您不限于只有一个跨越应用程序整个生命周期的大事务,您可以有多个连续的事务。
https://stackoverflow.com/questions/12987904
复制相似问题