通过主键中的字段从具有 EmbeddedId 的 JPARepository 中删除

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

目前我有一个 Spring 启动应用程序使用 JpaRepository 假设 EmployeePk 是名字,姓氏。有没有一种方法可以通过主键字段删除而不必指定自定义@Query?如果多人名为“John”,可以删除多行。

示例:

@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);
}

比如

void deleteByEmployeePkWhereFirstname(String firstname);

员工 class 和嵌入式 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;
}

以下应该有效:

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

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

或者如果您希望它更具可读性:

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

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

感谢您添加 Employee 和 EmployeePK 代码源。

由于您的实体中有 firstName 字段,因此您可以 使用派生的删除查询,从而避免必须显式声明 JPQL 查询

基于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:

您可以在您的存储库中添加此方法。

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

void deleteByEmployeePK_FirstName(String firstName);
}

您不需要 @Modify 注释,因为您不会使用 @Query 注释。

并将 @Entity 添加到您的实体,以便由数据库中的关联 table 映射。

@Entity
public class Employee {

@EmbeddedId
private EmployeePK employeePK;

private LocalDate birthDate;

 }