在这种情况下,answer_id是评级表中的外键,而answer_id是答案表中的主键。我需要删除答案,但“无法删除或更新父行:外键约束失败。发生错误。如何为此外键设置 ON DELETE SET NULL 选项。
@Entity
@Table(name = "ratings")
public class Ratings {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rating_id;
@Column(nullable = false, unique = false, length = 45)
private Short ratingValue;
@ManyToOne(cascade = fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
@ManyToOne(cascade = fetch = FetchType.LAZY)
@JoinColumn(name = "answer_id")
private Answer answer;
@ManyToOne(cascade = fetch = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
//getters and setters
@Entity
@Table(name = "answers")
public class Answer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long answer_id;
@Column(nullable = false, unique = false, length = 100)
private String fullAnswer;
/*Many to one mapping question*/
@ManyToOne(cascade = FetchType.LAZY)
@JoinColumn(name = "question_id")
private Question question;
/* Many to One mapping with users*/
@ManyToOne(cascade = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
//getters and setters
Hibernate 不支持 SET NULL 操作。
该功能请求于 2006 年创建,目前仍处于“开放”状态。
解决方法是在父实体上创建一个
@PreRemove
方法,将子实体中的外键设置为 NULL。我想如果您添加其他子实体,您必须修改您的 @PreRemove
方法。请参阅此答案中的示例: