1

I have a social networking app and a Subscription table/entity and User table/entity. I want to map a many to one relationship from Subscription to User but am not sure how best to capture the relation. Read up on this link on JPA Relationships

Here is my code so far Link to gist code there seems to be something wrong with my annotations.

I have a User table/entity with a user_id and name. My Subscription table has a subscriber(User) and a publisher(User) and an embedded composite key. How do you map the relation and then access the table/entity so I can add or remove subscriptions?

Linkx_lair
  • 569
  • 1
  • 9
  • 21
  • see this might helpful : https://stackoverflow.com/questions/7979382/how-to-create-join-table-with-jpa-annotations – Vinay Hegde Nov 29 '21 at 13:21
  • @vinay hegde the problem is i want it almost to be self referential. Like a user can subscribe to as many other users as he wants. And he can have 0 to many other follower (users). Most solutions came across use a join table of 2 separate parent entities. – Linkx_lair Nov 29 '21 at 13:35

1 Answers1

0

@ManyToOne and @OneToMany annotations should do the work for you.

Use List in the User class which will contain the subscriptions of each user.

  • So in my User class I have a list of subscriptions with a @OneToMany annotation. how do i do the mappings though? How can i map the user id with the publisher and subscriber fields? – Linkx_lair Nov 29 '21 at 14:39
  • You are gonna map the entities in Java. You will use the mappedBy property to specify the field in the other entity to map it with. https://www.baeldung.com/hibernate-one-to-many – Σωτήρης Ραφαήλ Nov 29 '21 at 14:43
  • how do you set the foreign key constraints? I used the OneToMany annotation in my User.subscribers and User.publication. And in my Subscription class I have '''User subscriberID''' and '''User publisherId'''. They are both ManyToOne. i want it to point to the user_id though of User table. See gist – Linkx_lair Nov 29 '21 at 14:48
  • Map them directly to the field in the User entity. – Σωτήρης Ραφαήλ Nov 29 '21 at 15:43