Tuesday, July 21, 2009

JPA Many-to-Many Self Referencing Problem


Problem:
A user entity U1 has five fans U2, U3, U4, U5 and U6. Again, U1 is also a fan of users U3 and U5. How can this scenario be implemented using JPA?

Observation:
This is a case of a Many-to-Many relationship and the User entity is referring itself (self join).

Solution:
Edit the User entity class as shown below -

@ManyToMany
@JoinTable(name="USER_FAN",
@JoinColumn(name="user_id", referencedColumnName="id"),
@JoinColumn(name="fan_id",referencedColumnName="id"))
private List myFans = new ArrayList();

@ManyToMany(mappedBy = "myF
ans")
private List admirerOf = new ArrayList();

Hope it helps someone who wants a quick answer to this question.