Home > Enterprise >  I cannot delete a record "Cannot delete or update a parent row: a foreign key constraint fails.
I cannot delete a record "Cannot delete or update a parent row: a foreign key constraint fails.

Time:06-11

I tried to delete a record in ratings table,then

Cannot add or update a child row: a foreign key constraint fails (fyprojectdb.ratings, CONSTRAINT FKdyash6f91887unaan9mj9b460 FOREIGN KEY (answer_id) REFERENCES answers (answer_id))

this error occured. How to fix this error. I have mapped both entities correctly.

@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 = CascadeType.ALL)
    @JoinColumn(name = "userId")
    private User user;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "answer_id")
    private Answer answer;

    @ManyToOne(cascade = CascadeType.ALL)
    @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 = CascadeType.REMOVE)
    @JoinColumn(name = "question_id")
    private Question question;

    /* Many to One mapping with users*/
    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "userId")
    private User user;
//getters and setters

CodePudding user response:

The reason is cascade = CascadeType.ALL here

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "userId")
private User user;

It means that the User has to be deleted after deleting any of Ratings.

Better to use RatingEntity for the entity and RATINGS for the table name.

General rule

Never use any cascade with @ManyToOne part of the association!

Also always use fetch = FetchType.LAZY with @ManyToOne.

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "userId")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "answer_id")
    private Answer answer;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "question_id")
    private Question question;
  • Related