编辑:修改问题以更好地反映问题。最初在这里发布问题
我有一个父 ( 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