Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self-reference field mapping in JPA

Lets say we have User entity class. User can be friends with other users. How can i map this self-reference collection field without creating a new entity called Connection or creating multiple entries in the database?

@Entity
public class User {
...
@ManyToMany
private Collection<User> friends;
...
}

USER_ID-FRIEND_ID
1 - 2
2 - 1 (duplicate... I don't need it)
like image 416
Hayati Guvence Avatar asked Dec 19 '11 19:12

Hayati Guvence


1 Answers

Following is snapshot from my code for ElementEntity:

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<ElementEntity> children;

@JoinColumn(name = "ParentId", referencedColumnName = "ElementId")
@ManyToOne(fetch = FetchType.LAZY)
private ElementEntity parent;

Where on database there are fields:

  • ElementId - primary key;
  • ParentId relation with parent
like image 119
Dewfy Avatar answered Oct 17 '22 01:10

Dewfy