Spring Data JPA deleteBy Column

In this blog post, we'll explore how to delete records based on a specific column value and integrate this functionality into a service layer.

1. Set up a Spring Boot project

Let's launch Spring Initializr and fill up the following project details: 

Project: Maven Project (or Gradle) 

Language: Java 

Packaging: Jar 

Java version: 17

Dependencies: Spring Data JPA, MySQL Driver, and Lombok

Download, extract the project, and import it to your favorite IDE.

2. Configure the MySQL database 

Let's open the src/main/resources/application.properties file and add the MySQL configuration properties:

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.hibernate.ddl-auto=update

Make sure that you change the MySQL database username and password as per your MySQL installation on your machine.

The spring.jpa.hibernate.ddl-auto=update line ensures that tables and columns get automatically created or updated based on your JPA entities.

3. Create JPA Entity - Employee

Let's create a simple Employee JPA entity that will map to the database table - employees:
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;

@Getter
@Setter
@ToString
@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
}
We are using below Lombok annotations to reduce the boilerplate code such as getter/setter methods:

@Getter: Generates getter methods for the fields of the class. 

@Setter: Generates setter methods for the fields of the class. 

3. Create Spring Data JPA Repository - EmployeeRepository

Let's create an EmployeeRepository interface that extends the JpaRepository interface from Spring Data JPA:

import com.springdatajpa.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

Deleting by Column Value 

To delete a employee based on their email (a unique field in our example), you'd define a method in the repository:
void deleteByEmail(String email);

With just this method declaration, Spring Data JPA will generate the necessary code to delete a customer record where the email column matches the provided email.

4. Service Layer Integration 

It's good practice to keep your business logic separate from your repository layer. Let's create a service class that leverages our repository:

import com.springdatajpa.springboot.repository.EmployeeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeService {

    private final EmployeeRepository employeeRepository;

    public EmployeeService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    @Transactional
    public void deleteEmployeeByEmail(String email) {
        employeeRepository.deleteByEmail(email);
    }
}

The @Service annotation marks this class as a Spring service component, making it eligible for component scanning. The @Transactional annotation ensures that the delete operation is wrapped within a transaction, which is crucial for database consistency.

Using @Transactional 

When executing a delete operation, it's essential to ensure that the operation is part of a transaction. You can annotate your service method (which calls the delete method) with @Transactional annotation:

    @Transactional
    public void deleteEmployeeByEmail(String email) {
        employeeRepository.deleteByEmail(email);
    }

 Or you can annotate the delete method directly in the repository:

import com.springdatajpa.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
      @Transactional
      void deleteByEmail(String email);
}

Conclusion

Spring Data JPA simplifies the process of deleting records based on specific column values, allowing you to focus on your application logic rather than writing and maintaining SQL or JPQL queries. Always ensure you understand the implications of deleting records, especially regarding database constraints and relationships.

Comments