JPA onetomany on same entity

廉价感情. 提交于 2019-12-12 03:34:50

问题


I am trying to create a entity as follows

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

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

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

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 ?


回答1:


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

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 + "]";
    }
}

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 ?

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

If yes , how to access it ?

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.

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


来源:https://stackoverflow.com/questions/35958335/jpa-onetomany-on-same-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!