piyush vijay
piyush vijay

Reputation: 13

JPA onetomany on same entity

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 ?

Upvotes: 0

Views: 3527

Answers (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

Upvotes: 2

Related Questions