Hibernate @OneToMany合并错误

时间:2015-02-10 16:18:50

标签: java hibernate postgresql one-to-many

我的应用程序遇到了问题:

我上面显示的是@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),一切正常。

数据库栏表:

row |  id
----+----
01  |  01

DB bar_foo_relation表:

row |bar_id|foo_id
----+------+------
01  |    01|    01
01  |    01|    02

DB foo table:

row |  id|foovalue
----+----+--------
01  |  01|foo
02  |  02|foo

但是,当我像这样放置新的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
    }
  ]
}

并在DB上调用manager.merge(bar)新的Foo实例: 数据库栏表:

row |  id
----+----
01  |  01

DB bar_foo_relation表:

row |bar_id|foo_id
----+------+------
01  |    01|    01
01  |    01|    02
01  |    01|    03  // New instance of Foo got persisted and is referenced here
01  |    01|    04  // New instance of Foo got persisted and is referenced here

DB foo table:

row |  id|foovalue
----+----+--------
01  |  01|foo
02  |  02|foo
02  |  03|null      // New instance of Foo without foovalue
02  |  04|null      // New instance of Foo without foovalue

新Foos的 fooValeu 列设置为null

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

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

1 个答案:

答案 0 :(得分:2)

尝试使用以下内容:

cascade = {CascadeType.PERSIST,CascadeType.MERGE}

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