2

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

1 Answers1

1

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.

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:

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828