remove related @OneToOne automatically in JPA
I'm using the following in JPA:
@Entity
class ParentClass {
@Id
@GeneratedValue
private long id;
...
@OneToOne(cascade = { cascade = { CascadeType.ALL },
mappedBy = "parentClass")
ChildClass child;
..
}
@Entity
class ChildClass {
@OneToOne
ParentClass 开发者_StackOverflowparentClass;
}
If I do a Query like createQuery("DELETE FROM ParentClass pc"), my child Class is not deleted automatically.
Can this be done with JPA-2.0? (I does work with @OneToMany relationships).
Bulk DML queries such as DELETE FROM ParentClass pc
ignore cascading options and orphanRemoval
, so if you actually need to do it in a bulk query, you can't configure JPA to delete ChildClass
es automatically.
However, you can configure your database to do it by adding a REFERENCES ... ON DELETE CASCADE
constraint to the foregin key of ChildClass
in your database schema.
In JPA2 you can set orphanRemoval = true
on @OneToOne annotation. However I would say that CascadeType.ALL should handle that. What if you call em.remove(parentClass) instead of calling query.
精彩评论