问题描述
我有一个servlet,当我用PU中指定的H2调用此方法时,每次调用它都会重新创建所有数据库结构.我只能将此方法调用1次吗,如果可以调用1次以上,该怎么办?
I have a servlet, and when I call this method with H2 specified in the PU, it re-creates all the database structure each time I call it. Can I only call this method 1 time, and if I can call it > 1 time, how do I do it?
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>
推荐答案
您将需要一个singleton方法来创建EntityManagerFactory,然后使用该Singleton实例获取EntityManager的新实例.注意:EntityManager不是线程安全的,您需要为每个线程获取一个新的EntityManager实例.下面是一个如何实现此目的的示例
You'll need a singleton method to create EntityManagerFactory and then get a new instance of EntityManager using that Singleton Instance. Note: EntityManager is not thread safe and you'll need to get a new EntityManager instance per thread. Below is an example of how to implement this
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()
And then to get the Entity manager simply call: JpaUtil.getEntityManager()
这篇关于调用Persistence.createEntityManagerFactory> 1次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!