您好我正在使用JPA2和Hibernate实现,我得到了一个简单的映射:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy = "user", cascade = ALL)
private List<SubscribedUser> subscribedUsers;
}
以及id类为
的第二个表(SubscribedUser)@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;
}
让我们假设我们有2条记录是subscribed_users表: 1.
user | subscribed_user
1 | 2
2
user | subscribed_user
2 | 1
问题是,当我删除id为1的User时,使用cascade选项正确删除了第一条记录,但是我收到了一个错误,因为在第二个条目中仍有对id = 1的User的引用在subscribed_users表中。是否有可能级联删除第二条记录?
由于
的Dawid
答案 0 :(得分:2)
据我了解,如果没有SubscribedUser
之间的双向关系,你就无法自动完成,所以添加如下内容:
@OneToMany(mappedBy = "subscribedUser", cascade = CascadeType.REMOVE)
private Set<SubscribedUser> dependentUsers;