gpt4 book ai didi

java - 调用 Persistence.createEntityManagerFactory > 1 次

转载 作者:行者123 更新时间:2023-12-01 20:53:46 24 4
gpt4 key购买 nike

我有一个 servlet,当我使用 PU 中指定的 H2 调用此方法时,每次调用它时它都会重新创建所有数据库结构。我只能调用这个方法1次吗?如果我可以调用它> 1次,我该怎么做?

entityManagerFactory = Persistence
.createEntityManagerFactory("MYPU");

用于持久性的 XML

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="MyJPAJAXRS" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>jdbc/myds</non-jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="javax.persistence.sql-load-script-source" value="META-INF/seed.sql"/>
</properties>
</persistence-unit>
</persistence>

最佳答案

您需要一个单例方法来创建 EntityManagerFactory,然后使用该单例实例获取 EntityManager 的新实例。注意:EntityManager 不是线程安全的,您需要为每个线程获取一个新的 EntityManager 实例。下面是如何实现这一点的示例

public class JpaUtil {

private static HashMap<String, String> properties = new HashMap<String, String>();
private volatile static EntityManagerFactory factory;

static {
properties.put("javax.persistence.jdbc.driver", System.getProperty("DRIVER"));
properties.put("javax.persistence.jdbc.user", System.getProperty("USER"));
properties.put("javax.persistence.jdbc.password", System.getProperty("PASSWORD"));
properties.put("javax.persistence.jdbc.url", System.getProperty("DATABASEURL"));
}

private static EntityManagerFactory getInstance() {
if (factory == null) {
synchronized (EntityManagerFactory.class) {
if (factory == null) {

factory = Persistence.createEntityManagerFactory("PU", properties);
}
}
}
return factory;
}

public static EntityManager getEntityManager() throws Exception {
return getInstance().createEntityManager();
}

}

然后要获取实体管理器,只需调用:JpaUtil.getEntityManager()

关于java - 调用 Persistence.createEntityManagerFactory > 1 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com