3

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;
}
Bizzaroerik
  • 33
  • 1
  • 6
  • 1
    can you post the code of the entiy Employee and the class EmployyPk ? In fact you can use methods defined by `JpaRepository` based in the entity fields to delete employees by firstName – Abenamor Dec 03 '21 at 23:44
  • Posted. Yes I was looking for something like you mentioned but couldn't find documentation when it involved an EmbeddedId. – Bizzaroerik Dec 05 '21 at 17:48

2 Answers2

3

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;

 }
Abenamor
  • 278
  • 1
  • 4
  • 15
2

The following should work:

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

    @Transactional
    @Modifying
    void deleteByEmployeePKFirstName(String firstname);
}

Or if you want it to be more readable:

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

    @Transactional
    @Modifying
    void deleteByEmployeePK_FirstName(String firstname);
}
João Dias
  • 16,277
  • 6
  • 33
  • 45