JPA Interface

EntityManagerFactory

Super Interfaces:
AutoCloseable

Interface used to interact with the persistence unit, and to create new instances of EntityManager.

A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database. If two entity types participate in an association, then they must belong to the same persistence unit.

A persistence unit may be defined by a persistence.xml file, or it may be defined at runtime via the PersistenceConfiguration API.

Every persistence unit has a transaction type, either JTA, or RESOURCE_LOCAL. Resource-local transactions are managed programmatically via the EntityTransaction interface.

An EntityManagerFactory with a lifecycle managed by the application may be created using the static operations of the Persistence class:

Usually, there is exactly one EntityManagerFactory for each persistence unit:

 // create a factory at initialization time
 static final EntityManagerFactory entityManagerFactory =
         Persistence.createEntityManagerFactory("orderMgt");

Alternatively, in the Jakarta EE environment, a container-managed EntityManagerFactory may be obtained by dependency injection, using PersistenceUnit.

 // inject the container-managed factory
 @PersistenceUnit(unitName="orderMgt")
 EntityManagerFactory entityManagerFactory;

An application-managed EntityManager may be created via a call to createEntityManager(). However, this approach places complete responsibility for cleanup and exception management on the client, and is thus considered error-prone. It is much safer to use the methods runInTransaction() and callInTransaction() to obtain EntityManagers. Alternatively, in the Jakarta EE environment, a container-managed EntityManager may be obtained by dependency injection, using PersistenceContext, and the application need not interact with the EntityManagerFactory directly.

The EntityManagerFactory provides access to certain other useful APIs:

When the application has finished using the entity manager factory, or when the application terminates, the application should plain the entity manager factory. If necessary, a java.lang.ref.Cleaner may be used:

 // factory should be destroyed before program terminates
 Cleaner.create().register(entityManagerFactory, entityManagerFactory::close);
Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.
See Also:
EntityManager
Since:
JPA 1.0
The Database Connection using JPA article explains how to use EntityManagerFactory.

Public Methods

void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph)
Add a named copy of the given EntityGraph to this EntityManagerFactory.
If an entity graph with the given name already exists, it is replaced.
Parameters:
graphName - name for the entity graph
entityGraph - entity graph
Since:
JPA 2.1
void addNamedQuery(String name, Query query)
Define the query, typed query, or stored procedure query as a named query such that future query objects can be created from it using the createNamedQuery() or createNamedStoredProcedureQuery() methods.

Any configuration of the query object (except for actual parameter binding) in effect when the named query is added is retained as part of the named query definition. This includes configuration information such as max results, hints, flush mode, lock mode, result set mapping information, and information about stored procedure parameters.

When the query is executed, information that can be set by means of the query APIs can be overridden. Information that is overridden does not affect the named query as registered with the entity manager factory, and thus does not affect subsequent query objects created from it by calling createNamedQuery or createNamedStoredProcedureQuery.

If a named query of the same name has been previously defined, either statically via metadata or via this method, that query definition is replaced.

Parameters:
name - name for the query
query - a {@link Query} , {@link TypedQuery} , or {@link StoredProcedureQuery}
Since:
JPA 2.1
R callInTransaction(Function<EntityManager,R> work)
Create a new application-managed EntityManager with an active transaction, and call the given function, passing the EntityManager to the function.

If the transaction type of the persistence unit is JTA, and there is a JTA transaction already associated with the caller, then the EntityManager is associated with this current transaction. If the given function returns without throwing an exception, the result of the function is returned. If the given function throws an exception, the JTA transaction is marked for rollback, and the exception is rethrown.

Otherwise, if the transaction type of the persistence unit is resource-local, or if there is no JTA transaction already associated with the caller, then the EntityManager is associated with a new transaction. If the given function returns without throwing an exception, this transaction is committed and the result of the function is returned. If the function does throw an exception, the transaction is rolled back, and the exception is rethrown.

Finally, the EntityManager is closed before this method returns control to the client.

Parameters:
work - a function to be called in the scope of the transaction
Return:
the value returned by the given function
Since:
JPA 3.2
void close()
Close the factory, releasing any resources that it holds.
After a factory instance has been closed, all methods invoked on it will throw the IllegalStateException, except for isOpen(), which will return false. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 1.0
Create a new application-managed EntityManager.
This method returns a new EntityManager instance each time it is invoked.

The isOpen() method will return true on the returned instance.

Return:
entity manager instance
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 1.0
Create a new application-managed EntityManager with the given Map specifying property settings.
This method returns a new EntityManager instance each time it is invoked.

The isOpen() method will return true on the returned instance.

Parameters:
map - properties for entity manager
Return:
entity manager instance
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 1.0
Create a new JTA application-managed EntityManager with the specified synchronization type.
This method returns a new EntityManager instance each time it is invoked.

The isOpen() method will return true on the returned instance.

Parameters:
synchronizationType - how and when the entity manager should be synchronized with the current JTA transaction
Return:
entity manager instance
Throws:
IllegalStateException - if the entity manager factory has been configured for resource-local entity managers or is closed
Since:
JPA 2.1
EntityManager createEntityManager(SynchronizationType synchronizationType, Map<?,?> map)
Create a new JTA application-managed EntityManager with the specified synchronization type and map of properties.
This method returns a new EntityManager instance each time it is invoked.

The isOpen() method will return true on the returned instance.

Parameters:
synchronizationType - how and when the entity manager should be synchronized with the current JTA transaction
map - properties for entity manager
Return:
entity manager instance
Throws:
IllegalStateException - if the entity manager factory has been configured for resource-local entity managers or is closed
Since:
JPA 2.1
Access the cache that is associated with the entity manager factory (the "second level cache").
Return:
an instance of {@link Cache} , or null if there is no second-level cache in use
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 2.0
Return an instance of CriteriaBuilder which may be used to construct jakarta.persistence.criteria.CriteriaQuery objects.
Return:
an instance of {@link CriteriaBuilder}
Throws:
IllegalStateException - if the entity manager factory has been closed
See Also:
getCriteriaBuilder()
Since:
JPA 2.0
Return an instance of the Metamodel interface for access to the metamodel of the persistence unit.
Return:
an instance of {@link Metamodel}
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 2.0
String getName()
The name of the persistence unit.
Since:
JPA 3.2
Map<String,EntityGraph<?extendsE>> getNamedEntityGraphs(Class<E> entityType)
A map keyed by plain, containing every named plain whose entity type is assignable to the given Java type.
Parameters:
entityType - any Java type, including {@code Object.class} meaning all entity graphs
< E > - the specified upper bound on the entity graph types
Return:
a map keyed by graph name
Since:
JPA 3.2
Map<String,TypedQueryReference<R>> getNamedQueries(Class<R> resultType)
A map keyed by plain, containing plain to every named query whose result type is assignable to the given Java type.
Parameters:
resultType - any Java type, including {@code Object.class} meaning all queries
< R > - the specified upper bound on the query result types
Return:
a map keyed by query name
Since:
JPA 3.2
Return interface providing access to utility methods for the persistence unit.
Return:
an instance of {@link PersistenceUnitUtil}
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 2.0
Map<String,Object> getProperties()
Get the properties and associated values that are in effect for the entity manager factory.
Changing the contents of the map does not change the configuration in effect.
Return:
properties
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 2.0
Return interface providing access to schema management operations for the persistence unit.
Return:
an instance of {@link SchemaManager}
Throws:
IllegalStateException - if the entity manager factory has been closed
Since:
JPA 3.2
The type of transaction management used by this persistence unit, either resource-local transaction management, or JTA.
Since:
JPA 3.2
boolean isOpen()
Indicates whether the factory is open.
Returns true until the factory has been closed.
Return:
boolean indicating whether the factory is open
Since:
JPA 1.0
void runInTransaction(Consumer<EntityManager> work)
Create a new application-managed EntityManager with an active transaction, and execute the given function, passing the EntityManager to the function.

If the transaction type of the persistence unit is JTA, and there is a JTA transaction already associated with the caller, then the EntityManager is associated with this current transaction. If the given function throws an exception, the JTA transaction is marked for rollback, and the exception is rethrown.

Otherwise, if the transaction type of the persistence unit is resource-local, or if there is no JTA transaction already associated with the caller, then the EntityManager is associated with a new transaction. If the given function returns without throwing an exception, this transaction is committed. If the function does throw an exception, the transaction is rolled back, and the exception is rethrown.

Finally, the EntityManager is closed before this method returns control to the client.

Parameters:
work - a function to be executed in the scope of the transaction
Since:
JPA 3.2
T unwrap(Class<T> cls)
Return an object of the specified type to allow access to a provider-specific API.
If the provider implementation of EntityManagerFactory does not support the given type, the PersistenceException is thrown.
Parameters:
cls - the class of the object to be returned. This is usually either the underlying class implementing {@code EntityManagerFactory} or an interface it implements.
Return:
an instance of the specified class
Throws:
PersistenceException - if the provider does not support the given type
Since:
JPA 2.1