0

I am using Spring Hibernate, when I try to delete rows which are stored in my db, it raises a DataIntegrityViolationException at a particular row. Why was a DataIntegrityViolationException thrown and how can I rectify that?

event.java :

@Id
@Column(name = "event_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "school1_score")
private Integer school1Score;

@Column(name = "school2_score")
private Integer school2Score;

activity.java :

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "event_id")
private Long event;

@Column(name = "category_id",  nullable = true)
private Long category;

@Column(name = "playlist_id",  nullable = true)
private Long playlist;

So basically, I try to delete a event without any activity and it works, when I have some activity with a event I get exception like this :

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (devnew.activity, CONSTRAINT FK8vaj54yaxyeog07uce4q17paj FOREIGN KEY (event_id) REFERENCES event (event_id))\r\n\tat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)\r\n\tat com.mysql.cj.jdbc.exceptions

Some ideas? about How to handle this exception??

  • Depending on your RDBMS you might be able to drop and recreate your foreign key constraints to allow cascading deletes. Alternatively, you will need to delete child records that reference the parent record prior to deleting the parent record. You would likely want to perform the series of deletes in a transaction. – j_b Nov 25 '22 at 14:52

0 Answers0