1438886
1438886

Reputation: 61

Join two tables with composite key in hibernate

I'm new to hibernate I couldn’t find a solution for this problem. I have two tables as follows.

User
----

Id
fistName
lastName


subscribed
----------

subscribedBy
subscribedTo

A user can subscribe to another user. Therefore both subscribedBy and subscribedTo are user ids and both columns together create a composite key.

For an example user1 has been subscribed to user2 and user3. I want to get the details about user2 and user3 using hibernate entity. But I don't need to get the details about subscribedBy user other than id.

Something like this,

public class subscribed {

    private long subscribedBy;
    private List< User> subscribedToUsers;
}

Upvotes: 1

Views: 455

Answers (1)

Nate Vaughan
Nate Vaughan

Reputation: 3839

You're looking for Hibernate's @ManyToMany. No need to create the join table; Hibernate will do that for you:

class User {
    @Id
    Long Id
    String fistName
    String lastName

    @ManyToMany
    Collection<User> subscriptions
}

Upvotes: 1

Related Questions