java - 如何在 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);
}
谁能帮我解决这个问题?
谢谢。
解决方案
无法执行语句;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
字段将不起作用,请标记字段@Id
并empId
用@NaturalId
推荐阅读
- php - PHP PDO 查询,优化超过 1000 万行的速度性能 MS ACCESS 数据库
- javascript - 为什么我的 innerHTML 不返回数组对象?
- checkbox - 从树视图 UWP 中获取选定的节点
- c# - 为什么在 c# 中启用计时器时不能做任何其他事情
- excel - ID,按 ID 计算 Y
- javascript - 当页面的提交按钮被点击时,组件是如何知道的?
- postgresql - 气流将 postgres 数据库的所有表导出到 BigQuery
- c# - Object resizing, storing variable and resizing from previous size in Unity C#
- opengl - OpenGL 和 X-Window 系统坐标映射
- spring - 异步调用从 redis 缓存中读取以减少响应时间