Reputation: 654
Hi I am using JPA2 with Hibernate implementation and I got a simple mapping like this :
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy = "user", cascade = ALL)
private List<SubscribedUser> subscribedUsers;
}
and a second table (SubscribedUser) with id class :
@Entity
@Table(name = "subscribed_users")
@IdClass(SubscribedUserId.class)
public class SubscribedUser {
@Id
@ManyToOne
@JoinColumn(name = "id_user", referencedColumnName = "id")
private User user;
@Id
@ManyToOne
@JoinColumn(name = "id_subscribed_user", referencedColumnName = "id")
private User subscribedUser;
}
Lets assume we got 2 records is a subscribed_users table : 1.
user | subscribed_user
1 | 2
2.
user | subscribed_user
2 | 1
The problem is that when I delete User with id = 1. the first record is deleted correctly with cascade option, but I got an error, because there are is a still reference to a User with id = 1 in the second entry in subscribed_users table. Is there a possibility to cascade delete also second record?
Thanks
Dawid
Upvotes: 0
Views: 415
Reputation: 242786
As far as I understand, you can't do it automatically without bidirectional relationship between SubscribedUser
's, so add something like this:
@OneToMany(mappedBy = "subscribedUser", cascade = CascadeType.REMOVE)
private Set<SubscribedUser> dependentUsers;
Upvotes: 2