Spring Data JPA EntityManager Examples (CRUD Operations)
- Details
- Written by Nam Ha Minh
- Last Updated on 21 November 2023   |   Print Email
- Understand briefly what EntityManager is, when and where you could use EntityManager with Spring Data JPA
- Code a Spring Boot console program that demonstrates using EntityManager for CRUD operations
1. What is EntityManager?
EntityManager is an interface provided by Java Persistence API (JPA) specification. We use EntityManager as a general-purpose DAO interface for managing lifecycle of entity instances, such as:- Create & Remove persistent entity instances
- Find entities by their primary key
- Query over entities
2. Setup a Spring Boot project with Spring Data JPA
Create a Java Maven project and update content of the pom.xml file as follows:<?xml version="1.0" encoding="UTF-8"?> <project ...> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.8</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>net.codejava</groupId> <artifactId>SpringJpaEntityManagerExamples</artifactId> <version>1.0</version> <name>SpringJpaEntityManagerExamples</name> <description>Learn how to use EntityManager with Spring Data JPA</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
spring.datasource.url=jdbc:mysql://localhost:3306/contactdb spring.datasource.username=root spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8DialectUpdate database URL, username, password according to your MySQL database settings. Note that you must create a new database schema named contactdb beforehand (using MySQL Workbench).Then update the main class to make it run as a console program, as follows:
package net.codejava; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringJpaEntityManagerExamplesApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(SpringJpaEntityManagerExamplesApplication.class, args); } @Override public void run(String... args) throws Exception { // code goes here... } }We’ll put more code into the main class later.
3. Code Entity Class
Next, code a Java class that acts as an entity that maps to a corresponding table in the database. Create the Contact class with the code as below:package net.codejava; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Contact { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "contact_id") private Integer id; private String name; private String email; private String address; private String phone; // getters and setters are not shown for brevity @Override public String toString() { return "Contact [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address + ", phone=" + phone + "]"; } }Now you can run the main program to let Hibernate create the corresponding table in the database, as we specified the property spring.jpa.hibernate.ddl-auto=update in the Spring application configuration file.
4. Inject an EntityManager object
With Spring Data JPA, you can inject an EntityManager object in a repository, service or controller class - depending on your need.Create the ContactRepository class and use @Autowired annotation to inject an EntityManager instance as follows:package net.codejava; import javax.persistence.EntityManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class ContactRepository { @Autowired private EntityManager entityManager; }At runtime, Spring Data JPA will initialize JPA EntityManagerFactory for persistence unit ‘default’. And the actual type of the entityManager object would be LocalContainerEntityManagerFactoryBean which wraps a Hibernate’s Session object.Alternatively, you can also use the @PersistenceContext annotation:
import javax.persistence.PersistenceContext; @Repository public class ContactRepository { @PersistenceContext private EntityManager entityManager; }Using @PersistenceContext, you can specify persistence unit name and additional properties (see its docs here). For a console application, both the ways will create an application-managed entity manager.
Spring Boot E-Commerce Ultimate Course
Learn to Build a complete shopping website using Java, Spring Boot, Thymeleaf, Bootstrap, jQuery and MySQL database
5. EntityManager Create Entity Example
Next, update the ContactRepository class - code the save() method that persists a new Contact object into the database. The code is as simple as below:package net.codejava; import javax.persistence.EntityManager; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class ContactRepository { @Autowired private EntityManager entityManager; @Transactional public void save(Contact contact) { entityManager.persist(contact); } }Here, we use the EntityManager’s persist() method. The passed Contact object will become a persistent object, which means its properties change is tracked by the entity manager, for synchronizing with the database.Then update the main class as follows, for testing purpose:
package net.codejava; @SpringBootApplication public class SpringJpaEntityManagerExamplesApplication implements CommandLineRunner { @Autowired private ContactRepository repo; public static void main(String[] args) { SpringApplication.run(SpringJpaEntityManagerExamplesApplication.class, args); } @Override public void run(String... args) throws Exception { createContact(); } private void createContact() { Contact newContact = new Contact(); newContact.setName("Peter Smith"); newContact.setEmail("peter.smith@gmail.com"); newContact.setAddress("New York, USA"); newContact.setPhone("123456-2111"); repo.save(newContact); } }Run this program, and you should see it inserts a new row into the contact table in database.
6. EntityManager Update Entity Example
To update an entity object, you should use the EntityManager’s merge() method. So add the following method into the repository class:@Transactional public Contact update(Contact contact) { return entityManager.merge(contact); }The merge() method synchronizes the changes with database, and it returns a persistent object. The passed object becomes unmanaged.Then update the main class as below, for testing update operation:
@Override public void run(String... args) throws Exception { updateContact(); } private void updateContact() { Contact existContact = new Contact(); existContact.setId(1); existContact.setName("Peter Smith"); existContact.setEmail("peter.smith@gmail.com"); existContact.setAddress("New York, USA"); existContact.setPhone("123456-2111"); Contact updatedContact = repo.update(existContact); }Run the program, and you should see the row ID 1 got updated in the contact table.
7. EntityManager Query Entities Example
The following code example shows how the EntityManager interface is used to perform a select query:package net.codejava; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class ContactRepository { @PersistenceContext private EntityManager entityManager; public List<Contact> findAll() { String jpql = "SELECT c FROM Contact c"; TypedQuery<Contact> query = entityManager.createQuery(jpql, Contact.class); return query.getResultList(); } }The findAll() method will return a List collection of Contact objects, mapped from the rows in the contact table in database. Note that the query is JPQL (Java Persistent Query Language) which is object-oriented query - not relational query.Then update the main class as follows - for testing a retrieval operation:
@Override public void run(String... args) throws Exception { listContacts(); } private void listContacts() { List<Contact> listContacts = repo.findAll(); listContacts.forEach(System.out::println); }Run the program, and you should see it prints the details of all contacts in the console.
8. EntityManager Find Entity by ID Example
The following code example shows how to code a method that finds an entity object by ID using EntityManager interface. Put the following method into the repository class:public Contact findById(Integer id) { return entityManager.find(Contact.class, id); }And update the main class for testing this retrieval operation:
@Override public void run(String... args) throws Exception { getContact(); } private void getContact() { Integer contactId = 1; Contact contact = repo.findById(contactId); System.out.println(contact); }Run this program, and you should see the details of the row ID 1 in the contact table printed in the console.
9. EntityManager Delete Entity Example
And lastly, I’d like to show a code snippet that implements the delete operation using EntityManager interface. Add the following method into the repository class:@Transactional public void delete(Integer contactId) { Contact contact = entityManager.find(Contact.class, contactId); entityManager.remove(contact); }And update the main class, for testing the delete operation:
@Override public void run(String... args) throws Exception { deleteContact(); } private void deleteContact() { Integer contactId = 1; repo.delete(contactId); }Run this program, and you should see the row ID 1 got deleted in the contact table.That’s my Spring Data JPA tutorial about using EntityManager for executing CRUD operations. You can use EntityManager as general-purpose DAO as shown in the examples. To see the coding in action, I recommend you watch my video below:
Recommended course:
Related Spring and Database Tutorials:
- JPA EntityManager: Understand Differences between Persist and Merge
- Spring Data JPA Custom Repository Example
- Understand Spring Data JPA with Simple Example
- Spring Data JPA Native Query Examples
- Spring MVC with JdbcTemplate Example
- How to configure Spring MVC JdbcTemplate with JNDI Data Source in Tomcat
- Spring and Hibernate Integration Tutorial (XML Configuration)
- Spring MVC + Spring Data JPA + Hibernate - CRUD Example
Comments