简体   繁体   中英

I cannot delete a record "Cannot delete or update a parent row: a foreign key constraint fails. How do I fix this?

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

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;

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