Friday, January 01, 2010

Hibernate3 Tip#4: One EntityManagerFactory Per Persistence Unit

If you use Hibernate3 for web applications, you must define a persistence unit (database connection and entity metadata from annotated classes or XML mappings). These are essentially the settings that describe how to connect to the database and describe the schema i.e. how tables are laid out and various relationships/constraints between the tables physically.

At runtime, you make persistence unit configuration available to the web application through an entity manager factory. Its main job is to instantiate entity managers for you that provide the persistence context in which you manipulate the database. Although you can create multiple factories based on a single persistence unit, it is not recommended. Instead, you ought to instantiate one statically-scoped entity manager factory and provide a thread-safe accessor that employs the singleton pattern to ensure there's always only one. That accessor initializes a new EMF if none exists and return EntityManager objects.

An example that uses a persistence unit called "puGeldzin":
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class DBUtil {
private static EntityManagerFactory emf;

public static synchronized EntityManager entityManager() {
if(emf == null) {
emf = Persistence
return emf.createEntityManager();

No comments: