在删除时使用外键设置为空

问题描述 投票:0回答:2

在这种情况下,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
java mysql spring-boot hibernate jpa
2个回答
1
投票

Hibernate 不支持 SET NULL 操作。

该功能请求于 2006 年创建,目前仍处于“开放”状态。

解决方法是在父实体上创建一个

@PreRemove
方法,将子实体中的外键设置为 NULL。我想如果您添加其他子实体,您必须修改您的
@PreRemove
方法。请参阅此答案中的示例:


0
投票

他们添加了这个。只要这样做:

@OnDelete(action = OnDeleteAction.SET_NULL)

休眠 jira HHH-15770

© www.soinside.com 2019 - 2024. All rights reserved.