- Spring Data JPA EntityManager Examples (CRUD Operations)
- 1. What is EntityManager?
- 2. Setup a Spring Boot project with Spring Data JPA
- 3. Code Entity Class
- 4. Inject an EntityManager object
- 5. EntityManager Create Entity Example
- 6. EntityManager Update Entity Example
- 7. EntityManager Query Entities Example
- 8. EntityManager Find Entity by ID Example
- 9. EntityManager Delete Entity Example
- Related Spring and Database Tutorials:
- About the Author:
- Add comment
- Comments
Spring Data JPA EntityManager Examples (CRUD Operations)
In this Spring Data JPA tutorial, you’ll learn how to use EntityManager to perform CRUD (Create, Retrieve, Update and Delete) operations on a MySQL database in a Spring Boot application. In details, I’ll help you:
- 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
Software programs: Java Development Kit (OpenJDK or Oracle JDK), any Java IDE (preferably Spring Tool Suite), MySQL database server & MySQL Workbench
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
An EntityManager object manages a set of entities that are defined by persistence unit. And the entity manager is responsible for tracking all entity objects for changes, and synchronizing the changes with database.
2. Setup a Spring Boot project with Spring Data JPA
4.0.0 org.springframework.boot spring-boot-starter-parent 2.5.8 net.codejava SpringJpaEntityManagerExamples 1.0 SpringJpaEntityManagerExamples Learn how to use EntityManager with Spring Data JPA 11 org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java runtime org.springframework.boot spring-boot-maven-plugin
You see, we use Spring Boot version 2.5.8 for the project. To use Spring Data JPA we need to declare the starter dependency spring-boot-starter-data-jpa . And to use MySQL database we need to have mysql-connector-java dependency which is MySQL JDBC driver.
Next, update the Spring application configuration file ( application.properties ) for data source information and Hibernate/JPA properties as follows:
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.MySQL8Dialect
Update 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. >>
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
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 @PersistenceContex t annotation:
import javax.persistence.PersistenceContext; @Repository public class ContactRepository
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.
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); >>
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)
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()
7. EntityManager Query Entities Example
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 ListfindAll() < String jpql = "SELECT c FROM Contact c"; TypedQueryquery = 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() < ListlistContacts = repo.findAll(); listContacts.forEach(System.out::println); >
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)
@Override public void run(String. args) throws Exception < getContact(); >private void getContact()
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)
@Override public void run(String. args) throws Exception < deleteContact(); >private void deleteContact()
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:
Related Spring and Database Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
Add comment
Comments
CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.
Copyright © 2012 — 2023 CodeJava.net, all rights reserved.