在同一实体上的JPA onetomany [英] JPA onetomany on same entity

查看:77
本文介绍了在同一实体上的JPA onetomany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试如下创建实体

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

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

离开JPA创建实体,我就可以将与朋友保持联系的人保留为空

Letting JPA create entity and i am able to persist person with friends as null

当尝试使用填充的朋友列表保存新朋友时,该关系在RDBMS中不可见,并且在保存时不会引发任何错误.

when trying to save a new person with friends list populated , the relation is not visible in RDBMS and its not throwing any error while saving.

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

Not able to figure out is the friend data actually getting stored ? If yes , how to access it ?

推荐答案

假定您有两个表PersonPerson_Friends. Person类的外观如下:

Assuming you have two tables, Person and Person_Friends. The Person class looks as below:

注意:为简单起见,我将IDENTITY用作GenerationType,将int用作id的数据类型.

NOTE: To keep it simple, I have used IDENTITY as GenerationType and int as datatype for 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 + "]";
    }
}

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

The code to save a sample Person object with 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表中找到朋友数据.

With this schema you should be able to find friends data in Person_Friends table.

如果是,如何访问它?

If yes , how to access it ?

加载Person对象(要查看其朋友数据)也应填充friends列表,尽管对于此映射而言比较懒惰.

Loading the Person object for whom you want to view the friends data should populate the friends list as well although lazily for this mapping.

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

In case you want to see the auto-generated tables used here, the DDLs below:

    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

这篇关于在同一实体上的JPA onetomany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆