Issue
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 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>
Solution
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();
}
}
And then to get the Entity manager simply call: JpaUtil.getEntityManager()
Answered By - Shivam Sinha
Answer Checked By - Cary Denson (JavaFixing Admin)