Hibernate Getting Started Guide
Hibernate Getting Started Guide
Table of Contents
Preface
1. Obtaining Hibernate
1.1. The Hibernate Modules/Artifacts
1.2. Release Bundle Downloads
1.3. Maven Repository Artifacts
2. Tutorial Using Native Hibernate APIs and hbm.xml Mapping
2.1. The Hibernate configuration file
2.2. The entity Java class
2.3. The mapping file
2.4. Example code
2.5. Take it further!
3. Tutorial Using Native Hibernate APIs and Annotation Mappings
3.1. The Hibernate configuration file
3.2. The annotated entity Java class
3.3. Example code
3.4. Take it further!
4. Tutorial Using the Java Persistence API (JPA)
4.1. persistence.xml
4.2. The annotated entity Java class
4.3. Example code
4.4. Take it further!
5. Tutorial Using Envers
5.1. persistence.xml
5.2. The annotated entity Java class
5.3. Example code
5.4. Take it further!
Preface preposition
gerund
Working with both Object-Oriented software and Relational Databases can be
cumbersome and time-consuming. Development costs are significantly higher due past participle clause
to a number of "paradigm mismatches" between how data is represented in objects
versus relational databases. Hibernate is an Object/Relational Mapping (ORM)
solution for Java environments. The term Object/Relational Mapping refers to the
present participle
technique of mapping data between an object model representation to a relational
data model representation. See http://en.wikipedia.org/wiki/Object- imperative clause
relational_mapping for a good high-level discussion. Also, Martin Fowler’s
OrmHate (http://martinfowler.com/bliki/OrmHate.html) article takes a look at many of
the mismatch problems. past participle clause
present participle clause
Although having a strong background in SQL is not required to use Hibernate,
having a basic understanding of the concepts can help you understand Hibernate
more quickly and fully. An understanding of data modeling principles is especially
important. Both http://www.agiledata.org/essays/dataModeling101.html and
http://en.wikipedia.org/wiki/Data_modeling are good starting points for
understanding these data modeling principles. If you are completely new to
database access in Java, https://www.marcobehler.com/guides/a-guide-to-accessing-
databases-in-java contains a good overview of the various parts, pieces and
options.
Hibernate takes care of the mapping from Java classes to database tables, and from
Java data types to SQL data types. In addition, it provides data query and retrieval
facilities. It can significantly reduce development time otherwise spent with
manual data handling in SQL and JDBC. Hibernate’s design goal is to relieve the
developer from 95% of common data persistence-related programming tasks by
eliminating the need for manual, hand-crafted data processing using SQL and
JDBC. However, unlike many other persistence solutions, Hibernate does not hide
the power of SQL from you and guarantees that your investment in relational
technology and knowledge is as valid as always.
Hibernate may not be the best solution for data-centric applications that only use
stored-procedures to implement the business logic in the database, it is most useful
with object-oriented domain models and business logic in the Java-based middle-
tier. However, Hibernate can certainly help you to remove or encapsulate vendor-
specific SQL code and streamlines the common task of translating result sets from
a tabular representation to a graph of objects.
The projects and code for the tutorials referenced in this guide are
available as hibernate-tutorials.zip
1. Obtaining Hibernate
1.1. The Hibernate Modules/Artifacts
Hibernate’s functionality is split into a number of modules/artifacts meant to
isolate dependencies (modularity).
hibernate-core
The main (core) Hibernate module. Defines its ORM features and APIs as well as
the various integration SPIs.
hibernate-envers
Hibernate’s historical entity versioning feature
hibernate-spatial
Hibernate’s Spatial/GIS data-type support
hibernate-osgi
Hibernate support for running in OSGi containers.
hibernate-agroal
Integrates the Agroal (http://agroal.github.io/) connection pooling library into
Hibernate
hibernate-c3p0
Integrates the C3P0 (http://www.mchange.com/projects/c3p0/) connection pooling
library into Hibernate
hibernate-hikaricp
Integrates the HikariCP (https://github.com/brettwooldridge/HikariCP/) connection
pooling library into Hibernate
hibernate-vibur
Integrates the Vibur DBCP (http://www.vibur.org/) connection pooling library into
Hibernate
hibernate-proxool
Integrates the Proxool (http://proxool.sourceforge.net/) connection pooling library
into Hibernate
hibernate-jcache
Integrates the JCache (https://jcp.org/en/jsr/detail?id=107$$) caching specification into
Hibernate, enabling any compliant implementation to become a second-level
cache provider.
hibernate-ehcache
Integrates the Ehcache (http://ehcache.org/) caching library into Hibernate as a
second-level cache provider.
You can download releases of Hibernate, in your chosen format, from the list at
https://sourceforge.net/projects/hibernate/files/hibernate-orm/. The release bundle
is structured as follows:
The lib/required/ directory contains the hibernate-core jar and all of its
dependencies. All of these jars are required to be available on your classpath no
matter which features of Hibernate are being used.
The lib/envers directory contains the hibernate-envers jar and all of its
dependencies (beyond those in lib/required/ and lib/jpa/ ).
The lib/osgi/ directory contains the hibernate-osgi jar and all of its
dependencies (beyond those in lib/required/ and lib/jpa/ )
The lib/optional/ directory contains the jars needed for the various
connection pooling and second-level cache integrations provided by Hibernate,
along with their dependencies.
The team responsible for the JBoss Maven repository maintains a number of Wiki
pages that contain important information:
The Hibernate ORM artifacts are published under the org.hibernate groupId.
Objectives
Bootstrap a Hibernate SessionFactory
The dialect property specifies the particular SQL variant with which Hibernate
will converse.
Finally, add the mapping file(s) for persistent classes to the configuration. The
resource attribute of the <mapping/> element causes Hibernate to attempt to
locate that mapping as a classpath resource using a java.lang.ClassLoader
lookup.
There are many ways and options to bootstrap a Hibernate SessionFactory . For
additional details, see the Native Bootstrapping topical guide.
Hibernate uses the mapping metadata to determine how to load and store objects
of the persistent class. The Hibernate mapping file is one choice for providing
Hibernate with this metadata.
XML
<class name="Event" table="EVENTS">
...
</class>
The table attribute names the database table which contains the data for this
entity.
Instances of the Event class are now mapped to rows in the EVENTS database
table.
Hibernate uses the property named by the <id/> element to uniquely identify
rows in the table.
The <id/> element here names the EVENT_ID column as the primary key of the
EVENTS table. It also identifies the id property of the Event class as the property
containing the identifier value.
XML
<property name="date" type="timestamp" column="EVENT_DATE"/>
<property name="title"/>
The two <property/> elements declare the remaining two persistent properties
of the Event class: date and title . The date property mapping includes the
column attribute, but the title does not. In the absence of a column attribute,
Hibernate uses the property name as the column name. This is appropriate for
title , but since date is a reserved keyword in most databases, you need to
specify a non-reserved word for the column name.
The title mapping also lacks a type attribute. The types declared and used in the
mapping files are neither Java data types nor SQL database types. Instead, they are
Hibernate mapping types, which are converters which translate between Java
and SQL data types. Hibernate attempts to determine the correct conversion and
mapping type autonomously if the type attribute is not specified in the mapping,
by using Java reflection to determine the Java type of the declared property and
using a default mapping type for that Java type.
In some cases this automatic detection might not chose the default you expect or
need, as seen with the date property. Hibernate cannot know if the property,
which is of type java.util.Date , should map to a SQL DATE, TIME, or
TIMESTAMP datatype. Full date and time information is preserved by mapping the
property to the timestamp converter, which identifies the converter class
org.hibernate.type.TimestampType .
Hibernate determines the mapping type using reflection when the
mapping files are processed. This process adds overhead in terms
of time and resources. If startup performance is important,
consider explicitly defining the type to use.
JAVA
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new
StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry
).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but
we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
The final step in the bootstrap process is to build the SessionFactory . The
SessionFactory is a thread-safe object that is instantiated once to serve the
entire application.
The SessionFactory acts as a factory for org.hibernate.Session instances,
which should be thought of as a corollary to a "unit of work".
JAVA
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Event( "Our very first event!", new Date() ) );
session.save( new Event( "A follow up event", new Date() ) );
session.getTransaction().commit();
session.close();
testBasicUsage() first creates some new Event objects and hands them over to
Hibernate for management, using the save() method. Hibernate now takes
responsibility to perform an INSERT on the database for each Event .
JAVA
session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery( "from Event" ).list();
for ( Event event : (List<Event>) result ) {
System.out.println( "Event (" + event.getDate() + ") : " +
event.getTitle() );
}
session.getTransaction().commit();
session.close();
Here we see an example of the Hibernate Query Language (HQL) to load all
existing Event objects from the database by generating the appropriate SELECT
SQL, sending it to the database and populating Event objects with the result set
data.
Objectives
Bootstrap a Hibernate SessionFactory
JAVA
@Entity
@Table( name = "EVENTS" )
public class Event {
...
}
JAVA
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Long getId() {
return id;
}
@javax.persistence.GeneratedValue and
@org.hibernate.annotations.GenericGenerator work in tandem to indicate
that Hibernate should use Hibernate’s increment generation strategy for this
entity’s identifier values.
JAVA
public String getTitle() {
return title;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "EVENT_DATE")
public Date getDate() {
return date;
}
As in The mapping file, the date property needs special handling to account for its
special naming and its SQL type.
Attributes of an entity are considered persistent by default when mapping with
annotations, which is why we don’t see any mapping information associated with
title .
Objectives
Bootstrap a JPA EntityManagerFactory
4.1. persistence.xml
The previous tutorials used the Hibernate-specific hibernate.cfg.xml
configuration file. JPA, however, defines a different bootstrap process that uses its
own configuration file named persistence.xml . This bootstrapping process is
defined by the JPA specification. In Java™ SE environments the persistence
provider (Hibernate in this case) is required to locate all JPA configuration files by
classpath lookup of the META-INF/persistence.xml resource name.
XML
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="org.hibernate.tutorial.jpa">
...
</persistence-unit>
</persistence>
persistence.xml files should provide a unique name for each "persistence unit".
Applications use this name to reference the configuration when obtaining an
javax.persistence.EntityManagerFactory reference.
JAVA
protected void setUp() throws Exception {
sessionFactory = Persistence.createEntityManagerFactory(
"org.hibernate.tutorial.jpa" );
}
JAVA
EntityManager entityManager = sessionFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( new Event( "Our very first event!", new Date()
) );
entityManager.persist( new Event( "A follow up event", new Date() ) );
entityManager.getTransaction().commit();
entityManager.close();
Again, the code is pretty similar to what we saw in Obtaining a list of entities.
Objectives
Annotate an entity as historical
Configure Envers
5.1. persistence.xml
This file was discussed in the JPA tutorial in persistence.xml, and is essentially the
same here.
Next, the find method retrieves specific revisions of the entity. The first call says
to find revision number 1 of Event with id 2. The second call says to find revision
number 2 of Event with id 2.
Write a query to retrieve only historical data which meets some criteria. Use
the User Guide to see how Envers queries are constructed.