In this article, we will see about Spring Data JPA CrudRepository deleteById() Example using Spring Boot and oracle.
The deleteById() method is used to delete an entity for a given id and it is available in CrudRepository interface. The CrudRepository extends Repository interface. In Spring Data JPA Repository is top-level interface in hierarchy. Here we are going to see deleteById() method of CrudRepository. The deleteById() method has been defined as below.
void deleteById(ID id);
Using deleteById() method we can delete a single record(entity) on basis of id. If we don’t provide any id it will throw IllegalArgumentException.
Internally deleteById() method use EntityManger’s remove() method. When we use deleteById(), internally first findById() method get called and entityManager.remove() get called(as below dummy sample).
public void deleteById(ID id) { delete(findById(id)); } public void delete(T entity) { em.remove(entity); }
Let’s see in below code how to use the Spring Data JPA CrudRepository deleteById() method for delete operation.
package com.javatute.impl; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.javatute.entity.Student; import com.javatute.repository.StudentRepository; import com.javatute.service.StudentService; @Service("studentServiceImpl") public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Transactional public Student saveStudent(Student student) { Student response = studentRepository.save(student); return response; } @Transactional(readOnly = true) public Student getStudent(int id ) { Optional<Student> studentResponse = studentRepository.findById(id); Student student = null; if(studentResponse.isPresent()) { student = studentResponse.get(); }else { throw new RuntimeException("No record found for given id: "+id); } return student; } public void deleteStudent(int id ) { studentRepository.deleteById(id); } }
Let’s see an example of Spring Data JPA CrudRepository deleteById() Example where we will use save() method for creating the entity, findById() to get a single record and deleteById() to delete a record.
Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next. Fill all details(GroupId – springdatadeletebyid, ArtifactId – springdatadeletebyid and name – springdatadeletebyid) 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>springdatadeletebyid</groupId> <artifactId>springdatadeletebyid</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springdatadeletebyid</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.
Directory structure –
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 save(@RequestBody Student student) { Student studentResponse = (Student) studentService.saveStudent(student); return studentResponse; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public Student getStudent(@PathVariable int id) { Student studentResponse = (Student) studentService.getStudent(id); return studentResponse; } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseBody public String deleteStudent(@PathVariable int id) { studentService.deleteStudent(id); return "student has been deleted successfully"; } }
StudentRepository.java – interface
package com.javatute.repository; import java.io.Serializable; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.javatute.entity.Student; @Repository public interface StudentRepository extends CrudRepository<Student, Serializable> { }
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 getStudent(int id); public void deleteStudent(int id); }
StudentServiceImpl.java
package com.javatute.impl; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.javatute.entity.Student; import com.javatute.repository.StudentRepository; import com.javatute.service.StudentService; @Service("studentServiceImpl") public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Transactional public Student saveStudent(Student student) { Student response = studentRepository.save(student); return response; } @Transactional(readOnly = true) public Student getStudent(int id ) { Optional<Student> studentResponse = studentRepository.findById(id); Student student = null; if(studentResponse.isPresent()) { student = studentResponse.get(); }else { throw new RuntimeException("No record found for given id: "+id); } return student; } public void deleteStudent(int id ) { studentRepository.deleteById(id); } }
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); } }
JpaConfig.java
package com.javatute.config; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @EnableJpaRepositories(basePackages = "com.javatute.repository") public class JpaConfig { }
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.hibernate.ddl-auto =create spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect server.port = 9091
Let’s run the SpringMain class(run as java application).
Perform save operation first using below REST API.
Request Data –
{ "name": "Hiteshdo", "rollNumber": "0126CS01", "university": "rgtu" }
Response data –
{ "id": 1, "name": "Hiteshdo", "rollNumber": "0126CS01", "university": "rgtu" }
Get operation.
API -http://localhost:9091/student/{id}
Delete operation.
Again perform get operation. We should get an error message. We can show an error message in proper way using global error handler. See Example here.
See brief about Spring Data JPA Repository hierarchy as below.
You may like.
- Spring Data CrudRepository saveAll() and findAll().
- CrudRepository findAllById() Example Using Spring Boot.
- Spring Data CrudRepository existsById()
- Spring Data JPA CrudRepository findById()
- Spring Data CrudRepository save() Method.
- Sorting in Spring Data JPA using Spring Boot.
- Spring Data JPA example using spring boot.
- Spring Data JPA and its benefit.
Other Spring Data JPA and Hibernate tutorials.
- @Version Annotation Example In Hibernate.
- Hibernate Validator Constraints Example Using Spring Boot.
- @Temporal Annotation Example In Hibernate/Jpa Using Spring Boot.
- Hibernate Table Per Concrete Class Spring Boot.
- Hibernate Table Per Subclass Inheritance Spring Boot.
- Hibernate Single Table Inheritance using Spring Boot.
- One To One Mapping Annotation Example in Hibernate/JPA using Spring Boot and Oracle.
- One To One Bidirectional Mapping Example In Hibernate/JPA Using Spring Boot and Oracle.
- One To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And Oracle.
- Many To One Unidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
- One To Many Bidirectional Mapping In Hibernate/JPA Annotation Example Using Spring Boot and Oracle.
- Many To Many Mapping Annotation Example In Hibernate/JPA Using Spring Boot And
Spring Data JPA findById() docs.