首页 > 解决方案 > 如何在 Spring Boot 的 OneToMany 关系中修复“无法执行语句;SQL [n/a];约束 [null]”

问题描述

我必须通过 API 执行删除操作。一旦我调用该 API,它就会给出一些嵌套异常,例如。

无法执行语句;SQL [不适用];约束[空];嵌套异常是 org.hibernate.exception.ConstraintViolationException:无法执行语句

无法执行语句;SQL [不适用];约束[空];嵌套异常是 org.hibernate.exception.ConstraintViolationException:无法执行语句

我的实体喜欢

@Entity
@Table(name = "EMPLOYEE")
public class Employee {
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    @Id
    private String emp_id;
    
    @OneToMany(targetEntity = SalaryAllowances.class, cascade = CascadeType.ALL, orphanRemoval = true)
    @Fetch(FetchMode.SELECT)
    @JoinColumn(name = "emp_id", referencedColumnName = "emp_id")
    private List<SalaryAllowances> salaryAllowances;
    private String firstName;
    private String lastName;
//...
}

映射的实体就像

@Entity
@Table(name = "Allowances")
public class SalaryAllowances {
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
    @Id
    private String allowanceId;
    private String name;
    private Double amount;
// ...
}

这是我的存储库类。

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {

    @Modifying
    @Query("DELETE FROM Employee e WHERE e.emp_id = :emp_id")
    void deleteEmployee(@Param("emp_id") String emp_id);

}

谁能帮我解决这个问题?

谢谢。

标签: javaspring-bootspring-data-jpaone-to-many

解决方案


无法执行语句;SQL [不适用];约束[空];嵌套异常是 org.hibernate.exception.ConstraintViolationException:无法执行语句

如果不查看完整的堆栈跟踪,这很难回答(但假设应该有Foreign key constraint error,因为您直接删除父行)

虽然,您不必编写要删除的查询,但使用 spring 数据存储库功能,您只需在调用代码中编写:

Employee employee = .... //Assuming you have queried the object from repository

// Some validation or logic here then

employeeRepository.delete(employee)

// It will delete SalaryAllowances entities associated with this employee, since you have CascadeMode.ALL

指定您自己的查询将不起作用,请在此处查看此答案以获取更多详细信息。

另外,@GeneratedValue没有@Id字段将不起作用,请标记字段@IdempId@NaturalId


推荐阅读