編輯:修改問題以更好地反映問題。最初發布問題hereJPA:級聯刪除不刪除子
我有一個父母(Context
)和一個孩子(User
)實體(ManyToOne關係)。在父級上級聯'刪除'不會刪除子級。代碼如下:
//Owning side - child
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = DBColumns.USER_NAME)
private String name;
@ManyToOne
@JoinColumn(name = DBColumns.CONTEXT_ID)
private Context context;
}
//parent
@Entity
public class Context {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = DBColumns.CONTEXT_NAME)
private String name;
@OneToMany(mappedBy = "context", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)
private Set<User> users = new HashSet<User>();
}
//usage
Context sampleContext = new Context("sampleContext");
em.persist(sampleContext);
User sampleUser = new User(sampleContext, "sampleUser");
em.persist(sampleUser);
em.remove(sampleContext); //should remove user as well but throws foreign key dependency error
。如果指定orphanRemoval = true,則不需要添加CascadeType.REMOVE。 (參見JSR338,第2.9節) – 8hZWKA 2016-10-08 10:54:54