Home > Software design >  ManyToMany - Cannot delete or update a parent row: a foreign key constraint fails (JAVA SPRING)
ManyToMany - Cannot delete or update a parent row: a foreign key constraint fails (JAVA SPRING)

Time:06-30

I did the merging of two columns into one and now when I try to delete some ethintent, Topic, throws me this error. The update works for me without any problems.

How I join the columns:

@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY)
@JoinTable(name = "subjects_topic", joinColumns = @JoinColumn(name = "subject_id"), inverseJoinColumns = @JoinColumn(name = "topic_id"))
@Valid
private Set<Topic> topic = new HashSet<>();

Error which i getting:

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (lms-database.subjects_topic, CONSTRAINT FKth8x407ityv1phgulkcqnlsmd FOREIGN KEY (topic_id) REFERENCES topic (id))

CodePudding user response:

You can try writing Subject entity like this

@Entity
public class Subject{

    @ManyToMany(cascade =CascadeType.ALL)
    @JoinTable(name = "subjects_topic", joinColumns = @JoinColumn(name = "subject_id"), inverseJoinColumns = @JoinColumn(name = "topic_id"))
    private Set<Topic> topic = new HashSet<>();
}

And writing Topicentity like

    @Entity
    public class Topic{
    
        @ManyToMany(cascade = CascadeType.ALL)
        @JoinTable(name="subjects_topic",
                joinColumns=@JoinColumn(name="topic_id"),
                inverseJoinColumns=@JoinColumn(name="subject_id")
            )
        private Set<Subject> subject= new HashSet<>();
  • Related