调用Persistence.createEntityManagerFactory> 1次

时间:2017-03-10 22:05:09

标签: java servlets h2

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

entityManagerFactory = Persistence
                    .createEntityManagerFactory("MYPU");

XML for persistence

<?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>

2 个答案:

答案 0 :(得分:2)

您需要一个单例方法来创建EntityManagerFactory,然后使用该Singleton实例获取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()

答案 1 :(得分:1)

你应该有一个单独的entityManagerFactory,然后你可以调用createEntityManager你需要多少时间。