Bootstrapping EntityManager in Hibernate

Learn to bootstrap the EntityManager and EntityManagerFactory using into a hibernate application using XML and programmatic configuration.

1. Setup

The minimum dependency we need to include is org.hibernate.orm:hibernate-core. Download its latest version from the maven repository.

<dependency>
   <groupId>org.hibernate.orm</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>6.0.0.Final</version>
</dependency>

2. Define Persistence Configuration

The persistence configuration goes into persistence.xml located at:

/src/main/resources/META-INF/persistence.xml

For testing purposes, we can place the file in the corresponding location at /src/test/resources/META-INF/persistence.xml.

In persistence.xml, we define the database connectivity information and the entity classes managed by the EntityManager. Use exclude-unlisted-classes if we don’t want to configure unlisted entities for this specific persistence unit.

Starting version 6.0.0.Final, Hibernate has moved from Java Persistence to Jakarta Persistence as defined by the Jakarta EE spec. This means we would need to use the Jakarata Persistence classes (jakarta.persistence.) instead of the Java Persistence classes (javax.persistence.).

Note that Jakarta spec also renames the JPA settings to 'jakarta.persistence.' and defines a new set of XSD namespaces for orm.xml and persistence.xml files.

In hibernate 5 and earlier versions, we can use the javax.persistence. package names.

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
    <persistence-unit name="H2DB">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.howtodoinjava.demo.entity.EmployeeEntity</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver"
                      value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url"
                      value="jdbc:h2:mem:test"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        </properties>
    </persistence-unit>
</persistence>

If we don’t want to provide a persistence.xml configuration file, Jakarta Persistence allows us to provide the option to supply the configuration using PersistenceUnitInfo class implementation. And then call HibernatePersistenceProvider.createContainerEntityManagerFactory() method.

3. Injecting EntityManager

3.1. Container-Managed EntityManager

When using frameworks like Spring, the container creates and injects the EntityManager in respective components. We only need to autowire the EntityManager field with @PersistenceContext annotation.

@PersistenceContext
EntityManager entityManager;

Note that in container-managed EntityManager, the container is responsible for beginning and committing the transactions. So we get rid of a lot of boilerplate code for creating and closing the EntityManager instances.

3.2. Application-Managed EntityManager

Use Persistence.createEntityManagerFactory() to programmatically create an instance of EntityManagerFactory.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("H2DB");

We call the createEntityManager() method where we want to access the EntityManager.

EntityManager em = emf.createEntityManager();

Note that in this setup, we are responsible for closing the EntityManager. Also, we are responsible for beginning and committing the transactions. Without committing the transaction, entity changes will not be persisted in the database.

EmployeeEntity emp = new EmployeeEntity();
emp.setEmail("demo-user@mail.com");
emp.setFirstName("demo");
emp.setLastName("user");

Assertions.assertNull(emp.getEmployeeId());

em.getTransaction().begin();
em.persist(emp);
em.getTransaction().commit();

Assertions.assertNotNull(emp.getEmployeeId());

4. Entity Annotations

As stated above, since hibernate 6, the persistence annotations have moved to package jakarta-persistence so we need to be careful while selecting the package names from where the annotations are imported.

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;
import java.io.Serial;
import java.io.Serializable;

@Entity
@Table(name = "TBL_EMPLOYEE")
public class EmployeeEntity implements Serializable {

  @Serial
  private static final long serialVersionUID = -1;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column
  private Integer employeeId;

  @Column
  private String email;

  @Column
  private String firstName;

  @Column
  private String lastName;

  //Getters and Setters
}

5. Conclusion

In this hibernate tutorial, we learned to initialize and use the EnitytManager from EntityManagerFactory using the XML configuration as well as the programmatic configuration.

We learned to use the Jakarta persistence API with the latest hibernate 6 changes.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode