Reputation: 13110
I have three Hibernate Entities:
Song represent a song file (e.g mp3 file), CoverArt contains songs coverart, a song can have multiple pieces of coverart
Within Song I define link to CoverArt as:
@OneToMany(fetch=FetchType.LAZY, cascade={CascadeType.ALL})
@JoinColumn(name = "recNo")
private List<CoverArt> coverArts;
Within CoverArt there is no link defined to Song, we just have
@Id
@GeneratedValue
private Integer id;
The application works okay, except when I want to empty the Song and CoverArt entities.
It doesn't happen consistently but if I try and delete from Song first
e.g
String hql = String.format("delete from CoverArt");
Query query = session.createQuery(hql);
query.executeUpdate();
hql = String.format("delete from Song");
query = session.createQuery(hql);
query.executeUpdate();
session.getTransaction().commit();
I get exception:
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_CBUK1UQ1D0DQAA077XH16SRX2: PUBLIC.SONG_COVERART FOREIGN KEY(COVERARTS_ID) REFERENCES PUBLIC.COVERART(ID) (13)"; SQL statement:
and if I try the other way
String hql = String.format("delete from Song");
Query query = session.createQuery(hql);
query.executeUpdate();
hql = String.format("delete from CoverArt");
query = session.createQuery(hql);
query.executeUpdate();
I get exception
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK_4B4O39V3RSF1IWWRIX6QQQTLK: PUBLIC.SONG_COVERART FOREIGN KEY(SONG_RECNO) REFERENCES PUBLIC.SONG(RECNO) (1)"; SQL statement:
So its impossible to empty the tables, CoverArt entity only exists as part of a Song so I assumed their would only be a Foreign Key from a COVER_ART table to SONG table and expected I could delete everything from CoverArt without a problem, but there is an interim table created SONG_COVERART that has foreign keys to both tables preventing deletion.
What am I doing wrong (using Hibernate 4.3.11)
Upvotes: 0
Views: 72
Reputation: 691755
Probably because in a previous version of your code didn't have the JoinColumn annotation, and Hibernate thus created a join table for this association, that you filled, but forgot to delete.
Upvotes: 1