Search code examples
javaspring-data-jpacrud-repository

Delete from a JPARepository with an EmbeddedId by a field in the primary key


Currently I have a Spring Boot application using JpaRepository<Employee, EmployeePk> where let's say EmployeePk is firstname, lastname. Is there a way to delete by Primary Key field without having to specify a custom @Query? It's ok to delete multiple rows if multiple people were named "John".

Example:

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, EmployeePk> {

    @Transactional
    @Modifying
    @Query(value = "DELETE FROM Employee e WHERE e.EmployeePk.firstname = :firstname ")
    void deleteAllByEeId(String firstname);
}

such as

void deleteByEmployeePkWhereFirstname(String firstname);

Employee class and Embedded PK

public class Employee {

    @EmbeddedId
    private EmployeePK employeePK;
    
    private LocalDate birthDate;

}

public class EmployeePK implements Serializable {

    public static final long serialVersionUID = 1L;

    private String firstName;

    private String lastName;
}

Solution

  • Thanks for adding the Employee and EmployeePK code source.

    Since you have the field firstName in your entity so you can use derived delete queries that let you avoid having to declare the JPQL query explicitly

    Based in spring data documentation

    Derived Delete Queries

    Spring Data JPA also supports derived delete queries that let you avoid having to declare the JPQL query explicitly, as shown in the following example:

    You can add this method in your repositroy.

    @Repository
    public interface EmployeeRepository extends JpaRepository<Employee, EmployeePK> {
    
    void deleteByEmployeePK_FirstName(String firstName);
    }
    

    You don't need @Modify annotation since you will not use @Query annotation.

    And add @Entity to your entity in order to be mapped by the associated table in the database.

    @Entity
    public class Employee {
    
    @EmbeddedId
    private EmployeePK employeePK;
    
    private LocalDate birthDate;
    
     }