Hibernate Javadoc (7.1.4.Final)
Hibernate ORM Javadocs
Hibernate is a library for object/relation mapping (ORM). It provides:
-
a native API centered around
SessionFactory,Session, andStatelessSession, -
an implementation of the Java (or Jakarta) Persistence API (JPA),
where the equivalent central interfaces are
EntityManagerFactoryandEntityManager, - a set of mapping annotations which augment the O/R mapping annotations defined by JPA, and which may be used with either API, and
- compile-time tooling for writing more type-safe code.
Native API
Along with SessionFactory and Session, applications
using the native API will often make use of the following interfaces:
HibernatePersistenceConfigurationorConfigurationto configure and bootstrap Hibernate,Cacheto manage the second-level cache,Transactionto control local transactions,SelectionQueryandMutationQueryto execute HQL queries,NativeQueryto execute native SQL queries,SelectionSpecificationandMutationSpecificationfor working with dynamic restrictions and ordering,Filterto manage filters,HibernateCriteriaBuilderto construct criteria queries, andSchemaManagerto execute DDL in tests.
JPA
The JPA interfaces are defined by the JPA specification. For details see the latest
specification along with the
API documentation
for the package jakarta.persistence.
Along with EntityManagerFactory and
EntityManager, programs based on the standard JPA API often use:
PersistenceandPersistenceConfigurationto bootstrap Hibernate via JPA,TypedQueryto execute queries,EntityGraphto control the boundaries of fetched data,EntityTransactionto control local transactions,Cacheto manage the second-level cache,SchemaManagerto execute DDL in tests,CriteriaBuilderto construct criteria queries,Metamodelto implement generic code which makes use of persistent entity classes in a reflective fashion, andCriteriaBuilderto build JPA criteria queries.
Note that since Hibernate 5.2, the native API extends the JPA API rather than wrapping it.
For example, SessionFactory extends EntityManagerFactory, and
Session extends EntityManager.
It's always possible to fall back from JPA interfaces to native APIs, by calling
entityManager.unwrap(Session.class),
entityManagerFactory.unwrap(SessionFactory.class),
or query.unwrap(Query.class). In certain cases
it's also possible to access native functionality by passing a
JPA-defined or
Hibernate-defined hint, at the cost of a
loss of type-safety.
These packages define additional extensions to the JPA APIs:
org.hibernate.query.criteriapackages extensions tojakarta.persistence.criteria, andorg.hibernate.metamodel.model.domainpackages extensions tojakarta.persistence.metamodel.
Mapping annotations
The mapping annotations defined by the JPA specification provide a foundation for expressing object/relational mappings in Hibernate and other JPA implementations.
The annotations in the package org.hibernate.annotations extend this foundation and
accommodate more specialized requirements. These annotation are not tied to the native API,
and may be used in conjunction with the JPA API.
The full power of Hibernate can only be unlocked via judicious use of these extra annotations.
XML-based mappings
Annotation-based mappings are the best choice for most users, but Hibernate offers XML-based mappings as an alternative.- The JPA-standard XML schema is orm_3_0.xsd.
- Hibernate extends this schema with some additional mapping elements. The extended schema is mapping-3.1.0.xsd.
- Prior to the existence of JPA, Hibernate had its own format for XML-based mappings, which still works, though it has not been improved in a long time. The DTD is hibernate-mapping-3.0.dtd
Bootstrapping Hibernate
There are four basic ways to obtain an instance of Hibernate:
-
as a JPA persistence provider, by using
Persistence.createEntityManagerFactory(java.lang.String), -
by using the "simplified"
ConfigurationAPI, -
for those who enjoy dirty hands, by using the APIs in
org.hibernate.boot, or -
in a container environment like
WildFly or Quarkus,
by letting the container take care of the bootstrap process and of injecting the
EntityManagerFactoryorSessionFactory.
All major Java application servers and microservice frameworks come with built-in support for
Hibernate. Such container environments also typically feature facilities to automatically
manage the lifecycle of a EntityManager or Session and its association with
container-managed transactions.
Example configuration files for JPA and native usage may be found here. A comprehensive list of configuration properties understood by Hibernate may be found in
the class AvailableSettings. Most sensible programs will only ever need
to use a tiny handful of them.
Annotations driving compile-time tooling
The annotations defined by org.hibernate.annotations.processing instruct the Metamodel
Generator to validate HQL at compile
time, and to automatically generate the implementation of
finder methods and
query methods.
Popular extension points
Hibernate offers an enormous wealth of extension points for customizing almost any aspect of its implementation. Most of these extension points are far too technical to be of interest to the typical application developer.
However, the following extension points are of quite general interest:
-
org.hibernate.boot.model.namingallows the quantity of repetitive O/R mapping metadata to be minimized via the use of naming strategies, -
org.hibernate.type.descriptor.jdbcandorg.hibernate.type.descriptor.javacontain the built-inJdbcTypes andJavaTypes for "compositional" basic attribute type mappings, -
org.hibernate.usertypedefines support for user-defined custom attribute types, -
org.hibernate.generatordefines support for generated attribute values, -
org.hibernate.context.spidefines support for context-bound "current" sessions and contextual multi-tenancy, and -
org.hibernate.binderallows for user-defined mapping annotations.
More advanced extension points include:
-
org.hibernate.dialectprovides a framework for modelling dialects of SQL, -
org.hibernate.cache.spidefines an SPI for integrating with second-level cache providers, -
org.hibernate.engine.jdbc.connections.spidefines an SPI for integrating with JDBC connection pools.
Finally, Hibernate ORM Core is itself a framework for advanced extensions like Hibernate Search,
Hibernate Reactive, and Envers, which do much more than just implementing a single well-defined
extension point. The starting points for such extensions are found in the packages
org.hibernate.integrator.spi and org.hibernate.event.spi.
Package categories
The organization of code into packages is based on the following classification:
-
API packages include classes and interfaces which are used directly by
a typical application. These packages never have
spinorinternalin their name, and are not under the namespaceorg.hibernate.testing. -
SPI packages include classes and interfaces which are used by integrators,
library developers, and framework developers to develop extensions to Hibernate, or to alter
its behavior in some way. These packages usually have
spiin their name. -
Some classes and interfaces are considered part of the internal implementation of Hibernate.
This category includes packages with
internalin their name, along with any class or interface annotated@Internal. Clients should avoid depending directly on these types. -
The
hibernate-testingmodule, and the namespaceorg.hibernate.testingcontain testing support used in the Hibernate test suite.
More information
Complete documentation may be found online at http://hibernate.org/orm/documentation/.
SessionFactory, which represents an instance of
Hibernate at runtime and is the source of new instances of
Session and StatelessSession,
the most important APIs exposing persistence-related operations for
entities.@Find
is used to generate finder methods using the Metamodel
Generator,
@HQL
and @SQL
are used to generate query methods using the Metamodel
Generator, and
CheckHQL
instructs the Query Validator to check all HQL queries
in the annotated package or type.AttributeBinder
and TypeBinder.cfg.xml files.cfg.xml files.orm.xml and hbm.xml mapping filesAttributeConverters.Metadata reference.hibernate-models model (ClassDetails, etc.)
to ultimately be bound into Hibernate's boot-time model.Dialect-specific aggregate column types,
including user-defined composite types, and JSON or XML types.SqmFunctionDescriptor
describing a range of relatively-sophisticated SQL functions available in various dialects.Dialect-specific identity column handling.Dialect-specific locking strategies.Dialect-specific pagination strategies.Dialect-specific sequence handling.AbstractSqlAstTranslator.JdbcType.Dialect-specific unique constraint definition.Connections.Connections from a
provider implemented as a service.JtaPlatform.Transaction.Session.JDBCException,
along with an SPI for interpreting product-specific SQLExceptions
arising from a JDBC driver into something more uniform and meaningful.Dialect-specific exception
interpretation and conversion.org.hibernate.graph.org.hibernate.id.enhanced,
contain the built-in id generators, all of which implement either
IdentifierGenerator or
PostInsertIdentifierGenerator.UuidGenerator.Service mechanism.ServiceLoader facility.org.hibernate.entity listeners.PropertyAccessStrategy.HibernateCriteriaBuilder
with additional functionality by registering a Service.Range framework.Restriction framework.NativeQuery, ProcedureCall,
and StoredProcedureQuery.SqlResultSetMapping, orm.xml,
mapping.xml or hbm.xml.SqmFunctionDescriptor handling.delete statements in the SQM tree.insert statements in the SQM tree.select statements in the SQM tree.update statements in the SQM tree.TransactionCoordinator
contract.TransactionCoordinator
based on JdbcResourceTransaction.TransactionCoordinator
based on JTA.Synchronization
callbacksSpatialDialects for CockroachDBdelete statements in a SQL tree.insert statements in a SQL tree.select statements in a SQL tree.update statements in a SQL tree.TableMutation
references for persisting entity mutation eventsJdbcOperation for model mutations.ResultSets into hydrated domain model graphs
based on a "load plan" defined by a "domain result graph", that is, one or more
DomainResult nodes with zero or more
Fetch nodes.SessionFactory and its
interaction with the database and second-level cache.Type is a strategy for mapping a Java
property type to a JDBC type or types.AttributeConverter instances as part of
the Hibernate Type system.JavaType.JdbcType.DdlType.DdlTypes.FormatMapper using Jackson.FormatMapper using Jakarta JSON.FormatMapper using JAXB.Types.org.hibernate.type.