同一实体上的 JPA onetomany

JPA onetomany on same entity

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

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

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

让 JPA 创建实体,我可以将有朋友的人保留为 null

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

无法确定好友数据是否实际存储?如果是,如何访问它?

假设您有两个 table,PersonPerson_FriendsPerson class 如下所示:

注意:为简单起见,我使用 IDENTITY 作为 GenerationTypeint 作为 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 table.

中找到好友数据

If yes , how to access it ?

加载要查看其好友数据的 Person 对象也应该填充 friends 列表,尽管对于此映射来说是懒惰的。

如果您想查看此处使用的自动生成的 table,请使用以下 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