JPA级联设置内容

时间:2012-01-10 17:44:17

标签: jpa associations one-to-many cascade many-to-one

你知道为什么:

class Owner {
  @OneToMany(mappedBy = "owner",
    cascade = CascadeType.ALL)
  public Set<Storage> storages
  ...

class Storage {
  @ManyToOne
  public Owner owner
  ...

无法正常工作:

Storage s = new Storage("S1")
Owner o = new Owner("O1")
o.storages.add(s)
...
em.persistAndFlush(o)
...
s = Storage.get...
assert(s.owner != null, "Storage does not have an Owner")
o = Order.get...
assert(!o.storages.isEmpty, "Owner does not have any Storage")

测试失败:

[info] - Storage *** FAILED ***
[info]   Storage does not have an Owner

我该如何解决?

1 个答案:

答案 0 :(得分:2)

这个问题每2天就会被问到一次。 JPA使用双向关联的拥有方来知道是否存在关联。拥有方是没有 mappedBy属性的一方。因此,要告诉JPA所有者和存储之间存在关联,您必须设置存储的所有者:

s.setOwner(o);