简体   繁体   中英

Use on delete set null for Foreign key

In this case answer_id is a foriegn key in ratings table and answer_id is primary key in answers table. I need to delete answers but "Cannot delete or update a parent row: a foreign key constraint fails. error occurred. How to set ON DELETE SET NULL option for this Foreign key.

@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

There is no support in Hibernate for a SET NULL action.

The feature request was created in 2006, and it's still in an "open" state. https://hibernate.atlassian.net/browse/HHH-4410

A workaround is to create a @PreRemove method on the parent entity, to set the foreign keys in the child entity to NULL. I suppose if you add other child entities, you'd have to modify your @PreRemove method. See example in this answer: https://stackoverflow.com/a/10030873/20860

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM