JPA Repository Delete By Field

Last updated on July 11th, 2024

In JPA Repository we can delete by field using query method deleteById() and custom query methods with delete or remove keywords for deleting records based on the property name of the JPA Entity class from the database table in the repository interface. In this topic, we will explore how to delete records by field with the JpaRepository using deleteById() and adding delete custom query methods.

delete by field

Methods to Delete By Field

1. Using deleteById() 

Using this query method we can delete records by the id field in JpaRepository.This method needs to pass the id as a parameter. We need to create a repository interface for the JPA Entity.

public interface UserRepository extends JpaRepository<User, Long> {

}

Create a service class for using this deleteById() method.

@Service

public class UserServiceImpl implements UserService {

  @Autowired

  private UserRepository userRepo;

  @Override

  public void deleteById(Long id) {

    userRepo.deleteById(id);

  }

2. Using Delete Custom Query Methods

We can add delete custom query methods with delete or remove keywords to delete records by field in the repository interface. These custom query methods must start to delete or remove keywords then add any word is optional followed by By keyword then add the property name of the JPA Entity class[delete….ByProperty_Name(Parameter) or remove….ByProperty_Name(Parameter)] based on the property_name which we want to delete records from the database table using JpaRepository.

public interface UserRepository extends JpaRepository < User, Long > {

  @Transactional

  int deleteUserByEmail(String email);

  @Transactional

  int removeUserByActive(boolean active);

}

Implementing JPA Repository Delete By Field

Make a Spring Boot restful web service Application to delete records by field in JpaRepository of Spring Data JPA step-by-step.

These are the following steps: 

  1. Creating a Spring Boot Starter Project
  2. Keep the IDE ready
  3. Maven Dependency
  4. Defining H2  Database Configuration
  5. Creating a JPA Entity class
  6. Creating a JPA Repository
  7. Creating a Service Interface
  8. Implementing Service Interface
  9. Creating a Controller class
  10. Run the Spring Boot Application and Check

1.  Creating a Spring Boot Starter Project

 We are creating a Spring Boot Application from the web tool Spring Initializr or you can make it from the IDE(STS, VS Code etc.). 

Add the following dependencies: 

  • Spring Web
  • Spring Data JPA
  • Lombok
  • H2 Database

2. Keep the IDE ready

      We are importing this created application into our Eclipse IDE’s workspace or you can import it into another IDE you use. You can refer to this article to create and set up the Spring Boot Project in Eclipse IDE.

Project Structure 

delete by field

3. Maven Dependency

Here is the complete pom.xml file for the Spring Boot Application.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.3.0</version>
		<relativePath/>
		<!-- lookup parent from repository -->
	</parent>
	<groupId>com.springjava</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

4. Defining H2 Database Configuration

We are configuring the H2 database configuration in the application.properties file.

application.properties

# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

5. Creating a JPA Entity class

We are creating a JPA Entity User with properties(id, name, email and active) to create a table in the database.

User.java

package com.springjava.entity;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

import jakarta.persistence.Table;

import lombok.Data;

@Data

@Entity

@Table(name = "user_tbl")

public class User {

  @Id

  @GeneratedValue(strategy = GenerationType.IDENTITY)

  private Long id;

  private String name;

  private String email;

  private boolean active;

}
  • This @Data annotation is used for a constructor, setter method, getter method, etc.
  • This @Entity annotation is used to create a table through Java code in the database. 
  • This @Table annotation is used to assign the name of the table which will be created in the database.
  • This @Id annotation is used to create a primary key of the entity class.
  • This @GeneratedValue(strategy = GenerationType.IDENTITY) annotation is used to generate increment value of the specified property of entity class

6. Creating a JPA Repository

We are creating a repository interface UserRepository for the User entity class. Adding some custom query methods with delete or remove keywords to delete records by field.

UserRepository.java

package com.springjava.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.transaction.annotation.Transactional;

import com.springjava.entity.User;

public interface UserRepository extends JpaRepository < User, Long > {

  @Transactional

  int deleteUserByEmail(String email);

  @Transactional

  int removeUserByActive(boolean active);

}
  • This @Transaction is used to help execute the above methods.

7. Creating a Service Interface

We are creating a Service Interface UserService to declare the methods.

UserService.java

package com.springjava.service;

import java.util.List;

import com.springjava.entity.User;

public interface UserService {

  void saveAll(List < User > userList);

  void deleteById(Long id);

  int deleteByEmail(String email);

  int deleteByActive(boolean active);

}

8. Implementing Service Interface

We are creating the Service class UserServiceImpl to implement the UserService interface and provide the implementation of its methods. This class is annotated with @Service annotation, which includes business functionality for this application. It injects the UserRepository into the class to use its method for deleting records by the field in the database table.

UserServiceImpl.java

package com.springjava.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.springjava.entity.User;

import com.springjava.repository.UserRepository;

@Service

public class UserServiceImpl implements UserService {

  @Autowired

  private UserRepository userRepo;

  @Override

  public void saveAll(List < User > userList) {

    userRepo.saveAll(userList);

  }

  @Override

  public void deleteById(Long id) {

    userRepo.deleteById(id);

  }

  @Override

  public int deleteByEmail(String email) {

    return userRepo.deleteUserByEmail(email);

  }

  @Override

  public int deleteByActive(boolean active) {

    return userRepo.removeUserByActive(active);

  }

}

9. Creating a Controller class

We are creating a Controller class UserController to create API endpoint methods that handle requests from the client.

UserController.java

package com.springjava.controller;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.DeleteMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.springjava.entity.User;

import com.springjava.service.UserService;

@RestController

@RequestMapping("/api/user")

public class UserController {

@Autowired

private UserService userService;

@PostMapping("/save-all")

public ResponseEntity<?> save(@RequestBody List<User> users) {

 Map<String, Object> respUser = new LinkedHashMap<String, Object>();

 userService.saveAll(users);

 respUser.put("status", 1);

 respUser.put("message", "Record is Saved Successfully!");

 return new ResponseEntity<>(respUser, HttpStatus.CREATED);

}

@DeleteMapping("/delete-by-id/{id}")

public ResponseEntity<?> deleteById(@PathVariable Long id) {

 Map<String, Object> respUser = new LinkedHashMap<String, Object>();

 userService.deleteById(id);

 respUser.put("status", 1);

 respUser.put("data", "Record is deleted successfully!");

 return new ResponseEntity<>(respUser, HttpStatus.OK);

}

@DeleteMapping("/delete-by-email/{email}")

public ResponseEntity<?> deleteByEmail(@PathVariable String email) {

 Map<String, Object> respUser = new LinkedHashMap<String, Object>();

 int count= userService.deleteByEmail(email);

 respUser.put("status", 1);

 respUser.put("data", count+" record is deleted successfully!");

 return new ResponseEntity<>(respUser, HttpStatus.OK);

}

@DeleteMapping("/delete-by-active/{active}")

public ResponseEntity<?> deleteByActive(@PathVariable boolean active) {

 Map<String, Object> respUser = new LinkedHashMap<String, Object>();

 int count= userService.deleteByActive(active);

 respUser.put("status", 1);

 respUser.put("data", count+" records are deleted successfully!");

 return new ResponseEntity<>(respUser, HttpStatus.OK);

}

}

➔  This class is annotated with @RestController annotation to make this class act as RestController for giving responses in JSON form.

➔ This @RequestMapping annotation to define the base URL for the application.

➔ These @PostMapping and @DeleteMapping annotations to handle HTTP requests from the client.

➔ This  ResponseEntity is used to represent the entire HTTP response.

➔   This @Autowired  annotation is used to inject UserService in the class.

➔ This@RequestBody annotation is used to take a JSON array in the save() method as the List of User class parameter.

10. Run the Spring Boot Application and Check

Right-click this Spring Boot application on the DemoApplication.java, then click Run As and select Java Application.

This application is running successfully then Spring Data JPA (internally uses Hibernate as a JPA provider) generates SQL statement in the console below here:

Hibernate: 
create table user_tbl (id bigint generated by default as identity, active boolean not null, email varchar(255), name varchar(255), primary key (id))

H2 Database Console

If we want to check the H2 database console then we need to browse this url on the browser.  

delete by field

JSON Array

We are creating a sample JSON Array to test the API http://localhost:8080/api/user/save-all.

[
  {
    "name": "Test",
    "email": "test@gmail.com",
    "active": true
  },
  {
    "name": "ABC",
    "email": "abc@gmail.com",
    "active": true
  },
  {
    "name": "DEF",
    "email": "def@gmail.com",
    "active": true
  },
  {
    "name": "XYZ",
    "email": "xyz@gmail.com",
    "active": true
  },
  {
    "name": "PQR",
    "email": "pqr@gmail.com",
    "active": true
  },
  {
    "name": "JKL",
    "email": "jkl@gmail.com",
    "active": true
  },
  {
    "name": "MNO",
    "email": "mno@gmail.com",
    "active": false
  }
]

Test the APIs on the Postman Tool

POST: http://localhost:8080/api/user/save-all

delete by field

This API hits then Spring Data JPA (internally uses Hibernate as a JPA provider) generates SQL statement in the console below here:

Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)
Hibernate: insert into user_tbl (active,email,name,id) values (?,?,?,default)

Check the Table

delete by field

DELETE: http://localhost:8080/api/user/delete-by-id/1

delete by field

This API hits then Spring Data JPA (internally uses Hibernate as a JPA provider) generates SQL statement in the console below here:

Hibernate: select u1_0.id,u1_0.active,u1_0.email,u1_0.name from user_tbl u1_0 where u1_0.id=?
Hibernate: delete from user_tbl where id=?

DELETE: http://localhost:8080/api/user/delete-by-email/xyz@gmail.com

This API hits then Spring Data JPA (internally uses Hibernate as a JPA provider) generates SQL statement in the console below here:

Hibernate: select u1_0.id,u1_0.active,u1_0.email,u1_0.name from user_tbl u1_0 where u1_0.email=?
Hibernate: delete from user_tbl where id=?

DELETE: http://localhost:8080/api/user/delete-by-active/true

delete by field

This API hits then Spring Data JPA (internally uses Hibernate as a JPA provider) generates SQL statement in the console below here:

Hibernate: select u1_0.id,u1_0.active,u1_0.email,u1_0.name from user_tbl u1_0 where u1_0.active=?
Hibernate: delete from user_tbl where id=?
Hibernate: delete from user_tbl where id=?
Hibernate: delete from user_tbl where id=?
Hibernate: delete from user_tbl where id=?
Hibernate: delete from user_tbl where id=?
Hibernate: delete from user_tbl where id=?

Conclusion

In this topic, we learnt how to delete by field records from a database table in JpaRepository using Spring Boot Restful web services.

Leave a Comment