gpt4 book ai didi

java - 同一实体上的 JPA 一对一

转载 作者:行者123 更新时间:2023-12-01 10:14:52 27 4
gpt4 key购买 nike

我正在尝试创建一个实体,如下所示

 @Data
public class Person
{
@Id
private String id;

@OneToMany(mappedBy="id")
private List<person> friends;
}

让 JPA 创建实体,我能够将有 friend 的人保留为空

当尝试保存填充了 friend 列表的新人时,该关系在 RDBMS 中不可见,并且在保存时不会抛出任何错误。

无法弄清楚好友数据是否真的被存储了?如果有,如何访问?

最佳答案

假设您有两个表,PersonPerson_FriendsPerson类如下所示:

注意:为了简单起见,我使用了 IDENTITYGenerationTypeint作为 id 的数据类型.

@Entity
class Person
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="Person_Friends")
List<Person> friends = new ArrayList<>();

@Override
public String toString() {
return "Person [id=" + id + ", friends=" + friends + "]";
}
}

保存示例的代码Person对象 friends :

entityManager.getTransaction().begin();
Person p = new Person();
p.friends.add(new Person());
p.friends.add(new Person());
p.friends.add(new Person());
p.friends.add(new Person());
entityManager.persist(p);
entityManager.getTransaction().commit();

Not able to figure out is the friend data actually getting stored ?

使用此架构,您应该能够在 Person_Friends 中找到好友数据。表。

If yes , how to access it ?

正在加载Person您想要查看其好友数据的对象应填充 friends尽管对于此映射来说是懒惰的,但也列出了。

如果您想查看此处使用的自动生成的表,请使用以下 DDL:

    create table Person (
id integer generated by default as identity,
primary key (id)
)

create table Person_Friends (
Person_id integer not null,
friends_id integer not null
)

alter table Person_Friends
add constraint UK_4ehyhs34ebu5gl6k8u5ckd2u7 unique (friends_id)

alter table Person_Friends
add constraint FKjvrny03ut8h70garyw5ehnlr7
foreign key (friends_id)
references Person

alter table Person_Friends
add constraint FK85ngln3801hk33fkhhsl7b8e7
foreign key (Person_id)
references Person

关于java - 同一实体上的 JPA 一对一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35958335/

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