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.

5 comments:

  1. Looks very promising,
    thanks for sharing this.

    Ray.

    ReplyDelete
  2. what is solution if this relationship have properties?

    ReplyDelete
  3. My scenario is bit complex.
    1. one application can provide services to many applications via different platform (ex. webmethod, web service, corba etc.. this is relationship property)
    2. one application can consume services provided by many applications

    ReplyDelete
  4. Can you give an example of how to store such an entity ?

    ReplyDelete
  5. Hi,

    Very nice, this solution useful for me. Thanks for amazing post. Your all comment about JBPM Web Application are welcome.

    Thanks.

    ReplyDelete