JPA EntityManager example in Spring Boot

In this tutorial, you will know how to use JPA EntityManager in Spring Boot example (with CRUD operations and query methods). I will show you:

  • Way to access JPA EntityManager in Spring Boot
  • How to use EntityManager methods: execute SQL query using createQuery and CRUD operations
  • JPA EntityManager query with parameters

Related Posts:
JPA Native Query example
Spring JPA Derived query example
Spring JPA @Query example
Spring Boot, Spring Data JPA – Rest CRUD API example
Spring Boot Pagination and Sorting example
Spring Boot File upload example with Multipart File
Spring Boot Authentication with Spring Security & JWT
Spring JPA + H2 example
Spring JPA + MySQL example
Spring JPA + PostgreSQL example
Spring JPA + Oracle example
Spring JPA + SQL Server example

Associations:
JPA One To One example with Hibernate in Spring Boot
JPA One To Many example with Hibernate and Spring Boot
JPA Many to Many example with Hibernate in Spring Boot


JPA EntityManager

JPA provides EntityManager interface that helps us persist an entity class into the database, manage lifecycle of entity instance such as create, remove, retrieve and query.

An EntityManager object manages a set of entities defined by Persistence Unit with the help of Persistence Context. Between our application and persistent storage, the Persistence Context is the first-level cache that tracks all entity objects for changes, and synchronizing the changes with database. Using the EntityManager is actually interacting with the Persistence Context.

EntityManager instance (and its configuration) is created by factory interface called EntityManagerFactory. Once the EntityManagerFactory is closed or application shutdowns, all its EntityManagers are closed.

How to access JPA Entity Manager?

We can inject an EntityManager object in a Spring Bean such as repository, service or controller… using @Autowired annotation.

@Repository
public class TutorialRepository {

  @Autowired
  private EntityManager entityManager;

}

Spring Data JPA will initialize EntityManagerFactory for default persistence unit at runtime. The EntityManager object will have LocalContainerEntityManagerFactoryBean type and wrap a Hibernate’s Session object.

Another way to access EntityManager is to use the @PersistenceContext annotation which can specify persistence unit name, type (transaction-scoped or extended-scoped) and other properties:

@Repository
public class TutorialRepository {

  @PersistenceContext
  private EntityManager entityManager;

}

JPA EntityManager example with Spring Boot

– Technology:

  • Java 8
  • Spring Boot 2.6.7 (with Spring Data JPA)
  • MySQL/PostgreSQL/H2 (embedded database)
  • Maven 3.8.1

– Project Structure:

jpa-entitymanager-spring-boot-project-structure

Let me explain it briefly.

  • Tutorial data model class correspond to entity and table tutorials.
  • TutorialRepository uses EntityManager for CRUD methods and custom finder methods. It will be autowired in SpringBootJpaEntitymanagerExampleApplication.
  • SpringBootJpaEntitymanagerExampleApplication is SpringBootApplication which implements CommandLineRunner. We will use TutorialRepository to run query and other methods here.
  • Configuration for Spring Datasource, JPA & Hibernate in application.properties.
  • pom.xml contains dependencies for Spring Boot and MySQL/PostgreSQL/H2 database.

Create & Setup Spring Boot project

Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.

Then open pom.xml and add these dependencies:

<!-- web for access H2 database UI -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

We also need to add one more dependency.
– If you want to use MySQL:

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

– or PostgreSQL:

<dependency>
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<scope>runtime</scope>
</dependency>

– or H2 (embedded database):

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

Configure Spring Datasource, JPA, Hibernate

Under src/main/resources folder, open application.properties and write these lines.

– For MySQL:

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update

– For PostgreSQL:

spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
  • spring.datasource.username & spring.datasource.password properties are the same as your database installation.
  • Spring Boot uses Hibernate for JPA implementation, we configure MySQL5InnoDBDialect for MySQL or PostgreSQLDialect for PostgreSQL
  • spring.jpa.hibernate.ddl-auto is used for database initialization. We set the value to update value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model will also trigger an update to the table. For production, this property should be validate.

– For H2 database:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update

spring.h2.console.enabled=true
# default path: h2-console
spring.h2.console.path=/h2-ui
  • spring.datasource.url: jdbc:h2:mem:[database-name] for In-memory database and jdbc:h2:file:[path/database-name] for disk-based database.
  • We configure H2Dialect for H2 Database
  • spring.h2.console.enabled=true tells the Spring to start H2 Database administration tool and you can access this tool on the browser: http://localhost:8080/h2-console.
  • spring.h2.console.path=/h2-ui is for H2 console’s url, so the default url http://localhost:8080/h2-console will change to http://localhost:8080/h2-ui.

Create Entity

In model package, we define Tutorial class.

Tutorial has four fields: id, title, description, published.

model/Tutorial.java

package com.bezkoder.spring.jpa.entitymanager.model;

import javax.persistence.*;

@Entity
@Table(name = "tutorials")
public class Tutorial {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column(name = "title")
  private String title;

  @Column(name = "description")
  private String description;

  @Column(name = "published")
  private boolean published;

  public Tutorial() {

  }

  public Tutorial(String title, String description, boolean published) {
    this.title = title;
    this.description = description;
    this.published = published;
  }

  // getters and setters
}

@Entity annotation indicates that the class is a persistent Java class.
@Table annotation provides the table that maps this entity.

@Id annotation is for the primary key.
@GeneratedValue annotation is used to define generation strategy for the primary key.

Define Repository with JPA EntityManager

Let’s create a repository to interact with database.
In repository package, create TutorialRepository class and inject EntityManager using @PersistenceContext annotation.

repository/TutorialRepository.java

package com.bezkoder.spring.jpa.entitymanager.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.bezkoder.spring.jpa.entitymanager.model.Tutorial;

@Repository
public class TutorialRepository {

  @PersistenceContext
  private EntityManager entityManager;

}

In this class, we will write query (with parameters) using EntityManager createQuery and other methods for CRUD operations.

JPA EntityManager createQuery

We can use EntityManager’s createQuery method for creating dynamic queries (Java Persistence Query Language – JPQL) directly within an application’s business logic.

public class TutorialRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public List<Tutorial> findAll() {
    TypedQuery<Tutorial> query = entityManager.createQuery("SELECT t FROM Tutorial t", Tutorial.class);
    return query.getResultList();
  }
}

The findAll() method returns a List of Tutorial objects, mapped from the rows in the tutorials table in database.

JPA EntityManager query with parameters

With createQuery method, we can also make query with parameters using Named parameters.

public class TutorialRepository {

  @PersistenceContext
  private EntityManager entityManager;

  public List<Tutorial> findByTitleContaining(String title) {
    TypedQuery<Tutorial> query = entityManager.createQuery(
        "SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :title,'%'))",
        Tutorial.class);
    return query.setParameter("title", title).getResultList();
  }

  public List<Tutorial> findByPublished(boolean isPublished) {
    TypedQuery<Tutorial> query = entityManager.createQuery(
        "SELECT t FROM Tutorial t WHERE t.published=:isPublished",
        Tutorial.class);
    return query.setParameter("isPublished", isPublished).getResultList();
  }

  public List<Tutorial> findByTitleAndPublished(String title, boolean isPublished) {
    TypedQuery<Tutorial> query = entityManager.createQuery(
        "SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :title,'%')) AND t.published=:isPublished",
        Tutorial.class);
    return query.setParameter("title", title).setParameter("isPublished", isPublished).getResultList();
  }
}

We declare the parameter with a colon followed by a string (:title, :isPublished). The actual value will be set at runtime.

Before executing the query, the parameter or parameters are set using setParameter method.

JPA EntityManager methods for CRUD operations

To perform CRUD (Create, Retrieve, Update, Delete) operations, we can use following JPA EntityManager methods:

  • persist: make given object managed and persistent. Its properties change will be tracked by the Entity Manager, for synchronizing with the database.
  • find: search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.
  • merge: merge the state of the given entity into the current Persistence Context.
  • remove: remove the entity instance.
public class TutorialRepository {

  @PersistenceContext
  private EntityManager entityManager;

  @Transactional
  public Tutorial save(Tutorial tutorial) {
    entityManager.persist(tutorial);
    return tutorial;
  }

  public Tutorial findById(long id) {
    Tutorial tutorial = (Tutorial) entityManager.find(Tutorial.class, id);
    return tutorial;
  }

  @Transactional
  public Tutorial update(Tutorial tutorial) {
    entityManager.merge(tutorial);
    return tutorial;
  }

  @Transactional
  public Tutorial deleteById(long id) {
    Tutorial tutorial = findById(id);
    if (tutorial != null) {
      entityManager.remove(tutorial);
    }

    return tutorial;
  }

  @Transactional
  public int deleteAll() {
    Query query = entityManager.createQuery("DELETE FROM Tutorial");
    return query.executeUpdate();
  }
}

For delete all entity instances, we use createQuery method.

Run Spring Boot with EntityManager example

Let’s open SpringBootJpaEntitymanagerExampleApplication.java, we will implement CommandLineRunner and autowire TutorialRepository interface to run JPA EntityManager methods here.

package com.bezkoder.spring.jpa.entitymanager;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.bezkoder.spring.jpa.entitymanager.model.Tutorial;
import com.bezkoder.spring.jpa.entitymanager.repository.TutorialRepository;

@SpringBootApplication
public class SpringBootJpaEntitymanagerExampleApplication implements CommandLineRunner {

  @Autowired
  TutorialRepository tutorialRepository;

  public static void main(String[] args) {
    SpringApplication.run(SpringBootJpaEntitymanagerExampleApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    tutorialRepository.deleteAll();

    tutorialRepository.save(new Tutorial("Spring Data", "Tut#1 Description", false));
    tutorialRepository.save(new Tutorial("Java Spring", "Tut#2 Description", false));
    tutorialRepository.save(new Tutorial("Hibernate", "Tut#3 Description", false));
    tutorialRepository.save(new Tutorial("Spring Boot", "Tut#4 Description", false));
    tutorialRepository.save(new Tutorial("Spring Data JPA", "Tut#5 Description", false));
    tutorialRepository.save(new Tutorial("JPA EntityManager", "Tut#6 Description", false));
    tutorialRepository.save(new Tutorial("Spring Security", "Tut#7 Description", false));

    List<Tutorial> tutorials = new ArrayList<>();

    tutorials = tutorialRepository.findAll();
    show(tutorials);
/*
Number of Items: 7
Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=false]
Tutorial [id=2, title=Java Spring, desc=Tut#2 Description, published=false]
Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=false]
Tutorial [id=4, title=Spring Boot, desc=Tut#4 Description, published=false]
Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=false]
Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
Tutorial [id=7, title=Spring Security, desc=Tut#7 Description, published=false]
*/

    Tutorial tutorial = tutorialRepository.findById(6);
    System.out.println(tutorial);
/*
Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
*/

    Tutorial tut1 = tutorials.get(0);
    tut1.setPublished(true);

    Tutorial tut3 = tutorials.get(2);
    tut3.setPublished(true);

    Tutorial tut5 = tutorials.get(4);
    tut5.setPublished(true);

    tutorialRepository.update(tut1);
    tutorialRepository.update(tut3);
    tutorialRepository.update(tut5);

    tutorials = tutorialRepository.findByTitleContaining("jpa");
    show(tutorials);
/*
Number of Items: 2
Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
*/

    tutorials = tutorialRepository.findByPublished(true);
    show(tutorials);
/*
Number of Items: 3
Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=true]
Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
*/

    tutorials = tutorialRepository.findByTitleAndPublished("data", true);
    show(tutorials);
/*
Number of Items: 2
Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
*/

    Tutorial deletedTutorial = tutorialRepository.deleteById(4);
    System.out.println(deletedTutorial);
/*
Tutorial [id=4, title=Spring Boot, desc=Tut#4 Description, published=false]
*/

    tutorials = tutorialRepository.findAll();
    show(tutorials);
/*
Number of Items: 6
Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
Tutorial [id=2, title=Java Spring, desc=Tut#2 Description, published=false]
Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=true]
Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
Tutorial [id=7, title=Spring Security, desc=Tut#7 Description, published=false]
*/

    int numberOfDeletedRows = tutorialRepository.deleteAll();
    System.out.println(numberOfDeletedRows);
/*
6
*/

    tutorials = tutorialRepository.findAll();
    show(tutorials);
/*
Number of Items: 0
*/
  }

  private void show(List<Tutorial> tutorials) {
    System.out.println("Number of Items: " + tutorials.size());
    tutorials.forEach(System.out::println);
  }
}

Conclusion

Today we’ve known how to use JPA EntityManager in Spring Boot example.

You can continue to write CRUD Rest APIs with:
Spring Boot, Spring Data JPA – Rest CRUD API example

If you want to write Unit Test for the JPA Repository:
Spring Boot Unit Test for JPA Repositiory with @DataJpaTest

You can also know:
– how to deploy this Spring Boot App on AWS (for free) with this tutorial.
– dockerize with Docker Compose: Spring Boot and MySQL example
– way to upload an Excel file and store the data in MySQL database with this post
– upload CSV file and store the data in MySQL with this post.

Happy learning! See you again.

Further Reading

Using @Query annotation:
Spring JPA @Query example with Spring Boot

Or Native Query:
Spring JPA Native Query example with Spring Boot

Or Derived query:
Spring JPA Derived query example in Spring Boot

Associations:
JPA One To One example with Hibernate in Spring Boot
JPA One To Many example with Hibernate and Spring Boot
JPA Many to Many example with Hibernate in Spring Boot

You can apply this implementation in following tutorials:
Spring JPA + H2 example
Spring JPA + MySQL example
Spring JPA + PostgreSQL example
Spring JPA + Oracle example
Spring JPA + SQL Server example

Fullstack CRUD App:
Vue + Spring Boot example
Angular 8 + Spring Boot example
Angular 10 + Spring Boot example
Angular 11 + Spring Boot example
Angular 12 + Spring Boot example
Angular 13 + Spring Boot example
React + Spring Boot example