<?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.
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.
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
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.
@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.
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.
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.
@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: