M
M
Muiron2016-02-06 18:37:39
Java
Muiron, 2016-02-06 18:37:39

How to set up a Many To Many relationship within the same entity in Spring Jpa?

Hello.
I suspect that the question is a little stupid, but still.
I am making a server using Spring 4.2.4 and Spring Data Jpa, the model is something like a social network, there is an entity (let's call it "User" conditionally), you need to store data on who this user subscribed to, and, accordingly, who is subscribed to this user . That is, there is a Many To Many connection, but there is one problem - the same entity is located on both sides of it.
I'm thinking of coding it like this:

@ManyToMany
    @JoinTable(name="following_follower",
            joinColumns = @JoinColumn(name="follower_id", referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name="following_id", referencedColumnName="id"))
    private Set<User> following;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "following")
    private Set<User> followers;

But it confuses whether there will be problems with processing such a connection.
Or is it better to go the other way: remove this relationship from Jpa altogether and write a link table and a repository for it manually?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
goshan_p, 2016-02-08
@goshan_p

I will not tell you how it is implemented in Java. But such a database model exists for sure.

K
kosmom, 2016-02-12
@kosmom

And why is it embarrassing? The entity class can be the same, it should work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question