gpt4 book ai didi

java - Hibernate @OneToMany 合并错误

转载 作者:行者123 更新时间:2023-12-02 04:59:24 25 4
gpt4 key购买 nike

我的应用程序遇到问题如下:

我有一个 @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 table:

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

DB foo table:

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

But, when I put new Foo instances like this:

{
"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栏表:

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

数据库 bar_foo_relation 表:

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

数据库foo表:

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

新 Foos 的列 fooValeu 设置为 null

我不知道为什么会这样。有人可以帮我解释一下吗?

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

最佳答案

尝试使用以下内容:

级联={CascadeType.PERSIST,CascadeType.MERGE}

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

关于java - Hibernate @OneToMany 合并错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com