0

I would like to implement a User-Friend relationship in Hibernate/JPA, something like:

 class User {
    Set<User> friends;
 }

Let's say that user A and user B are friends. If user A unfriends user B, list of friends of User B should not contain user A anymore.

Is there any clean way to model this kind of relation in Hibernate/JPA (and, of course, in the underlying DB tables)?

Giulio Pulina
  • 344
  • 4
  • 15
  • I believe that association `many-to-many` is pretty handful for your case. Check this out: https://www.baeldung.com/hibernate-many-to-many You need to create one more table and store relationships between users into it. – NikMashei Nov 26 '21 at 15:01
  • @Zogger I am looking for a clever way to store the relationship using the many-to-many association. In fact, the problem I'm facing is also well described here https://wordeology.com/computer/representing-symmetric-relations-in-a-relational-database.html – Giulio Pulina Nov 26 '21 at 15:11
  • 1
    I agree, link what you shared contains a good point about duplicating data. But also if you would use int32 to store these relationships then it isn't a big deal. Maybe some answers from this link help you with your issue: https://dba.stackexchange.com/questions/10199/how-should-i-design-a-relationship-table-for-fr – NikMashei Nov 26 '21 at 15:48
  • besides increasing the required storage, data duplication introduces a consistency problem (each time an operation is performed, two rows in the table must be added/removed: A, B and B,A) and I wanted to understand if Hibernate/JPA has some built-in features to handle such cases – Giulio Pulina Nov 26 '21 at 16:34

0 Answers0