【问题标题】:Hibernate @OneToMany merge error休眠@OneToMany合并错误
【发布时间】:2015-02-10 16:18:49
【问题描述】:

我的申请遇到了问题:

我有一个如上所示的@OneToMany 关系:

酒吧类:

@Entity
public class Bar {

    @Id
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    @JoinTable(name = "bar_foo_relation",
        joinColumns = { @JoinColumn(name = "id", referencedColumnName = "bar_id") },
        inverseJoinColumns = { @JoinColumn(name = "id", referencedColumnName = "foo_id") } )
    private List<Foo> fooList;

    // Getters & Setters

}

Foo 类:

@Entity
public class Foo {

    @Id
    private Long id;

    private String fooValue;

    // Getters & Setters

}

当我创建一个新的 Bar 实例并填充 fooList 时,如下所示:

{
  "id": null,
  "fooList": [
    {
      "id": null,
      "fooValue": "foo"
    },
    {
      "id": null,
      "fooValue": "foo"
    }
  ]
}

我打电话给manager.persist(bar),一切正常。

数据库条形表:

行 | ID ----+---- 01 | 01

数据库 bar_foo_relation 表:

行 |bar_id|foo_id --+--------+------ 01 | 01| 01 01 | 01| 02

数据库 foo 表:

行 | id|foo 值 ----+----+-------- 01 | 01|富 02 | 02|富

但是,当我像这样放置新的 Foo 实例时:

{
  "id": 1,
  "fooList": [
    {
      "id": 1,
      "fooValue": "foo"
    },
    {
      "id": 2,
      "fooValue": "foo"
    },
    // New instance of Foo to persist
    {
      "id": null,
      "fooValue": "foo" // fooValue is setted
    },
    // New instance of Foo to persist
    {
      "id": null,
      "fooValue": "foo" // fooValue is setted
    }
  ]
}

并调用manager.merge(bar) Foo 的新实例,这发生在 DB 上: DB条形表:

行 | ID ----+---- 01 | 01

数据库 bar_foo_relation 表:

行 |bar_id|foo_id --+--------+------ 01 | 01| 01 01 | 01| 02 01 | 01| 03 // Foo 的新实例被持久化并在此处引用 01 | 01| 04 // Foo 的新实例被持久化并在此处引用

数据库 foo 表:

行 | id|foo 值 ----+----+-------- 01 | 01|富 02 | 02|富 02 | 03|null // 没有 foovalue 的 Foo 的新实例 02 | 04|null // 没有 foovalue 的 Foo 的新实例

新Foos的fooValeu列设置为null

我不知道为什么会这样。有人可以澄清一下吗?

我的环境是: Java 1.7 PostgreSQL 9.3 休眠4.3.6.Final

【问题讨论】:

  • 如果在其中添加 CascadeType.MERGE 会发生什么? (cascade={CascadeType.REFRESH, CascadeType.MERGE}) 您试图通过在 Bar 上调用 merge 来保存 Foo 的新实例这一事实似乎不正确。
  • 谢谢。我添加了 CascadeType.MERGE 并且它的工作。回答问题。我会投票并标记为已解决。

标签: java hibernate postgresql one-to-many


【解决方案1】:

尝试使用以下方法:

cascade={CascadeType.PERSIST, CascadeType.MERGE}

我相信您看到的行为(尽管我不是 100% 确定)是当您对非持久化子对象调用合并时,实体管理器知道存在关联对象,但因为它们不是持久化对象的一部分context Foo 的默认构造函数在幕后调用。告诉您的父对象级联合并操作或手动保存子对象将阻止这种情况发生。

【讨论】:

  • Foo 实体不会自行持久化。只有 Bar 实体... mappedBy 选项需要引用 Foo 类的属性,但实体上没有要引用的属性。
  • 上面的评论引用了我之前的答案,该答案已被编辑为更正确的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 2019-12-24
相关资源
最近更新 更多