gpt4 book ai didi

java - JPA @OneToMany -> 父 - 子引用(外键)

转载 作者:IT老高 更新时间:2023-10-28 13:04:00 26 4
gpt4 key购买 nike

我有一个关于从子实体 ir 引用 ParentEntities 的问题如果我有这样的事情:

父.java:

@Entity(name ="Parent")
public class Parent {
@Id
@Generate.....
@Column
private int id;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parent")
private Set<Child> children;

simple ... getter and setter ...
}

还有 Child.java:

@Entity(name ="Child")
public class Child{
@Id
@Generate....
@Column
private int id;

@ManyToOne
private Parent parent;

... simple getter an setter
}

将创建以下表格:

Parent:
int id

Child:
int id
int parent_id (foreign key: parent.id)

好的,到目前为止,一切都很好。但是当谈到使用 Java 中的这个引用时,我想,你可以做这样的事情。

@Transactional
public void test() {
Parent parent = new Parent();
Child child = new Child();

Set<Child> children = new HashSet<Child>();
children.add(child);
parent.setChildren(children);
entityManager.persist(parent);
}

这在数据库中导致了这一点:

Parent:
id
100

Child
id paren_id
101 100

但事实并非如此,您必须明确地将 Parent 设置为 Child(我认为,框架可能会自行完成)。

所以数据库中真正的内容是这样的:

Parent:
id
100

Child
id paren_id
101 (null)

因为我没有将父级设置为子级。所以我的问题:

我真的必须做某事吗?像这样?

父.java:

...
setChildren(Set<Child> children) {
for (Child child : children) {
child.setParent.(this);
}

this.children = children;
}
...

编辑:

根据快速回复,我能够通过在引用拥有实体上使用 @JoinColumn 来解决这个问题。如果我们从上面举个例子,我做了某事。像这样:

父.java:

@Entity(name ="Parent")
public class Parent {
@Id
@Generate.....
@Column
private int id;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name= "paren_id")
private Set<Child> children;

simple ... getter and setter ...
}

还有 Child.java:

@Entity(name ="Child")
public class Child{
@Id
@Generate....
@Column
private int id;

... simple getter an setter
}

现在如果我们这样做:

@Transactional
public void test() {
Parent parent = new Parent();
Child child = new Child();

Set<Child> children = new HashSet<Child>();
children.add(child);

parent.setChildren(children);
entityManager.persist(parent);
}

Reference 由 Parent 正确设置:

Parent:
id
100

Child
id paren_id
101 100

最佳答案

Do I really have to do sth. like this?

这是一种策略,是的。

在双向关系中,关系有“拥有”和“非拥有”的一面。因为在您的情况下,拥有方位于 Child 上,因此您需要在那里设置关系以使其保持不变。拥有方通常由您指定 @JoinColumn 的位置确定,但看起来您并没有使用该注释,因此很可能是从您使用 mappedBy< 的事实推断出来的Parent 注释中。

您可以read a lot more about this here .

关于java - JPA @OneToMany -> 父 - 子引用(外键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533676/

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