JPA EntityManager CRUD example Using Spring Boot

In this post, we will see the JPA EntityManager CRUD example Using Spring Boot and Oracle. We are going to use the below methods for the JPA EntityManager CRUD example.

  • EntityManager persist() method
  • EntityManager merge() method
  • EntityManager find() method
  • EntityManager remove() method

We will have below REST API to test JPA EntityManager CRUD example.

Request Method Rest APIs/Endpoints
POSThttp://localhost:9091/student/save
PUThttp://localhost:9091/student/update
GEThttp://localhost:9091/student/find/{id}
DELETEhttp://localhost:9091/student/delete

Implementation class.

package com.javatute.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@PersistenceContext
	private EntityManager entityManger;

	@Transactional
	public Student saveStudent(Student student) {
		entityManger.persist(student);
		return student;
	}

	@Transactional
	public Student updateStudent(Student student) {
		entityManger.merge(student);
		return student;
	}

	@Transactional
	public Student deleteStudent(Student student) {
		if (entityManger.contains(student)) {
			entityManger.remove(student);
		} else {
			entityManger.remove(entityManger.merge(student));
		}

		return student;
	}

	@Transactional
	public Student getStudent(int id) {
		Student response = (Student) entityManger.find(Student.class, id);
		return response;
	}

}

Did you notice in above code snippet we are checking entityManger.contains(student)?in deleteStudent() method if we don’t check this will get java.lang.IllegalArgumentException: Removing a detached instance.

JPA EntityManager CRUD example Using Spring Boot and Oracle.

Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – entitymanager, ArtifactId – entitymanager and name – entitymanager) and click on finish. Keep packaging as the jar.

Modify pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>entitymanager</groupId>
	<artifactId>entitymanager</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>entitymanager</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<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>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK.

If you see any error for oracle dependency then follow these steps.

Let’s see the directory structure of JPA EntityManager persist() method example as below.

Directory structure –

JPA EntityManager remove() example Using Spring Boot

Let’s see about JPA EntityManager find() method.

Student.java

package com.javatute.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

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

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

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRollNumber() {
		return rollNumber;
	}

	public void setRollNumber(String rollNumber) {
		this.rollNumber = rollNumber;
	}

	public String getUniversity() {
		return university;
	}

	public void setUniversity(String university) {
		this.university = university;
	}

}

StudentController.java

package com.javatute.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.javatute.entity.Student;
import com.javatute.service.StudentService;

@RestController
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private StudentService studentService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Student saveStudent(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.saveStudent(student);
		return studentResponse;
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	@ResponseBody
	public Student updateStudent(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.updateStudent(student);
		return studentResponse;
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@ResponseBody
	public Student deleteStudent(@RequestBody Student student) {
		Student studentResponse = (Student) studentService.deleteStudent(student);
		return studentResponse;
	}
	

	@RequestMapping(value = "/find/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Student getStudent(@PathVariable int id) {

		Student studentResponse = (Student) studentService.getStudent(id);
		return studentResponse;
	}

}

We have seen controller and serviceimpl, interface for JPA EntityManager CRUD example Using Spring Boot.

Note – See more details about @Controller and RestController here.

StudentService.java – interface

package com.javatute.service;

import org.springframework.stereotype.Component;

import com.javatute.entity.Student;

@Component
public interface StudentService {
	public Student saveStudent(Student student);

	public Student deleteStudent(Student student);
	
	public Student updateStudent(Student student);

	public Student getStudent(int id);

}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

StudentServiceImpl.java

package com.javatute.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.javatute.entity.Student;
import com.javatute.service.StudentService;

@Service("studentServiceImpl")
public class StudentServiceImpl implements StudentService {

	@PersistenceContext
	private EntityManager entityManger;

	@Transactional
	public Student saveStudent(Student student) {
		entityManger.persist(student);
		return student;
	}

	@Transactional
	public Student updateStudent(Student student) {
		entityManger.merge(student);
		return student;
	}

	@Transactional
	public Student deleteStudent(Student student) {
		if (entityManger.contains(student)) {
			entityManger.remove(student);
		} else {
			entityManger.remove(entityManger.merge(student));
		}

		return student;
	}

	@Transactional
	public Student getStudent(int id) {
		Student response = (Student) entityManger.find(Student.class, id);
		return response;
	}

}

SpringMain.java

package com.javatute.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = "com.*")
@EntityScan("com.javatute.entity")
public class SpringMain {
	public static void main(String[] args) {

		SpringApplication.run(SpringMain.class, args);
	}

}

Note – See more details about @ComponentScan here.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

#show sql values
logging.level.org.hibernate.type.descriptor.sql=trace

#hibernate.show_sql = true
#spring.jpa.hibernate.logging.level.sql =FINE
#show sql statement
#logging.level.org.hibernate.SQL=debug

Let’s run the SpringMain class(run as java application).

Perform save operation first using below REST API.

POST – http://localhost:9091/student/save

    {
        "name": "john",
        "rollNumber": "120",
        "university":"rgtu"
    }

Response Data.

    {
        "id": 1,
        "name": "john",
        "rollNumber": "120",
        "university": "rgtu"
    }

Below query get generated while saving student entity using persist() method.

Hibernate:
insert
into
student
(name, roll_number, university, id)
values
(?, ?, ?, ?)

PUT – http://localhost:9091/student/update/

JPA EntityManager CRUD example Using Spring Boot

Hibernate:
update
student
set
name=?,
roll_number=?,
university=?
where
id=?

DELETE – http://localhost:9091/student/delete

JPA EntityManager remove() example

delete
from
student
where
id=?

localhost:9091/student/find/{id}

JPA EntityManager persist() method

Query genrated for above operation using JPA Entitymanger find() method.

Hibernate:
select
student0_.id as id1_0_0_,
student0_.name as name2_0_0_,
student0_.roll_number as roll_number3_0_0_,
student0_.university as university4_0_0_
from
student student0_
where
student0_.id=?

That’s all about JPA EntityManager CRUD example Using Spring Boot and Oracle.

You may like.

Other Spring Data JPA and Hibernate tutorials.

EntityManger docs.

Summary – We have seen JPA EntityManager CRUD example Using Spring Boot and Oracle.