JPA级联 设置内容

发布于 2024-12-26 01:08:31 字数 653 浏览 1 评论 0原文

你知道为什么这个:

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

我该如何修复它?

Do you know why this:

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

class Storage {
  @ManyToOne
  public Owner owner
  ...

doesn't work as expected:

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")

The test fails:

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

How can I fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烙印 2025-01-02 01:08:31

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

s.setOwner(o);

This question gets asked once every 2 days. JPA uses the owning side of a bidirectional association to know if an association exists. The owning side is the side where there is no mappedBy attribute. So, to tell JPA that an association exists between owner and storage, you must set the owner of the storage:

s.setOwner(o);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文