Creating one EntityManagerFactory by application
When controlling database transactions programmatically one EntityManagerFactory per application is usually
used. This is the optimal approach since loading an EntityManagerFactory has a high performance cost; JPA will
analyze the database, validate entities and perform several other tasks when creating a new EntityManagerFactory.
Thus it is unviable to create a new EntityManagerFactory per transaction.
Below is a code that can be used:
import javax.persistence.*;
public abstract class ConnectionFactory {
private ConnectionFactory() {
}
private static EntityManagerFactory entityManagerFactory;
public static EntityManager getEntityManager(){
if (entityManagerFactory == null){
entityManagerFactory = Persistence.createEntityManagerFactory("MyPersistenceUnit");
}
return entityManagerFactory.createEntityManager();
}
}
When controlling database transactions programmatically one EntityManagerFactory per application is usually
used. This is the optimal approach since loading an EntityManagerFactory has a high performance cost; JPA will
analyze the database, validate entities and perform several other tasks when creating a new EntityManagerFactory.
Thus it is unviable to create a new EntityManagerFactory per transaction.
Below is a code that can be used:
import javax.persistence.*;
public abstract class ConnectionFactory {
private ConnectionFactory() {
}
private static EntityManagerFactory entityManagerFactory;
public static EntityManager getEntityManager(){
if (entityManagerFactory == null){
entityManagerFactory = Persistence.createEntityManagerFactory("MyPersistenceUnit");
}
return entityManagerFactory.createEntityManager();
}
}
No comments:
Post a Comment