你知道为什么:
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
我该如何解决?
答案 0 :(得分:2)
这个问题每2天就会被问到一次。 JPA使用双向关联的拥有方来知道是否存在关联。拥有方是没有 mappedBy
属性的一方。因此,要告诉JPA所有者和存储之间存在关联,您必须设置存储的所有者:
s.setOwner(o);