Using
JBoss 4.0.4RC1
MySQL 5.0.18
I have 2 classes PlayList and Song. A PlayList has a List of Songs but a song doesn't know about a PlayList and a Song can be in only 1 playlist or not have a playlist at all. So we have a one-to-many unidirectional relationship.
Code:
@Entity
@Table(uniqueConstraints=
{@UniqueConstraint(columnNames={"name"})})
public class PlayList {
private Long id;
private String name;
private List<Song> songs;
...
public void setId(Long id) {
this.id = id;
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE})
public List<Song> getSongs() {
return songs;
}
}
@Entity
@Table(uniqueConstraints=
{@UniqueConstraint(columnNames={"name"})})
public class Song {
private Long id;
private String name;
...
public void setId(Long id) {
this.id = id;
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
}
When the schema is generated 3 tables result:
Code:
create table PlayList (id bigint not null auto_increment, name varchar(255), primary key (id), unique (name))
create table PlayList_Song (PlayList_id bigint not null, songs_id bigint not null, unique (songs_id))
create table Song (id bigint not null auto_increment, name varchar(255), primary key (id), unique (name))
The problem comes when I try to delete a song, which is associated with a playlist
Code:
entityManager.remove( aSong );
Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails ('music/playlist_song`, CONSTRAINT `FK1428A70D9548933E` FOREIGN KEY (`songs_id`) REFERENCES `song` (`id`))
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:647)
at org.jboss.resource.adapter.jdbc.WrappedStatement.executeBatch(WrappedStatement.java:517)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)
... 57 more
How can I tell hibernate that it's ok to remove a song from the playlist_song table?