Package jakarta.persistence


package jakarta.persistence
Defines the core APIs for the management for persistence and object/relational mapping.
  • EntityManager is the central interface used to interact with a stateful persistence context. An instance of EntityManager must never be shared across independent units of work nor between concurrently executing threads.
  • EntityAgent provides an alternative more direct approach to interaction with the database, with no intermediating persistence context. An instance of EntityAgent must never be shared between concurrently executing threads.
  • TypedQuery, Statement, and StoredProcedureQuery allow control over the execution of queries, statememts, and stored procedures.
  • EntityManagerFactory acts as a factory for instances of EntityManager and EntityAgent and provides access to other APIs including Cache, SchemaManager, CriteriaBuilder, Metamodel, and PersistenceUnitUtil. There is usally one instance of EntityManager for each configured persistence unit.
  • Persistence is an entry point for construction of an EntityManagerFactory in Java SE and defines standard configuration properties.
  • As an alternative to the use of persistence.xml, PersistenceConfiguration allows a persistence unit to be configured programatically.
  • SchemaManager provides operations for direct programmatic management of the database schema.
  • Cache provides operations for direct management of the second-level cache.
  • EntityGraph provides a way to specify the boundaries of an operation on entity types.

The following example demonstrates one way to quickly configure and start Jakarta Persistence in Java SE:

// configure the persistence unit
var library = new PersistenceConfiguration("Library");
library.nonJtaDataSource("java:global/jdbc/LibraryDatabase");
library.defaultToOneFetchType(FetchType.LAZY);
// register the entity classes
List.of(Book.class, Author.class, Publisher.class)
	       .forEach(library::managedClass);
// create the entity manager factory
try (var factory = config.createEntityManagerFactory()) {
	   // export the schema and test data
    factory.getSchemaManager().create(true);
    // start a transaction and obtain an entity agent
    factory.runInTransaction(EntityAgent.class, agent -> {
        // obtain an entity instance by providing its primary key
        var book = agent.get(Book.class, isbn);
        ...
    });
}
Note, however, that createEntityManagerFactory is an expensive operation which should be called just once for each persistence unit in the application program.

Furthermore, this package provides a suite of annotation types which may be used: