Following Followers in Spring

Viewed 3022

I am trying to develop a Following Followers functionality in a Spring Boot application. i search for example and I saw this one, which made perfect sense at the beginning:

https://github.com/SoichiSumi/Twitter-Clone/blob/master/src/main/java/yoyoyousei/twitter/clone/domain/model/User.java

My User had a ManyToMany relation of following, like this....

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "relation",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "following_id"))
private List<User> following;

I developed my controllers, JSPs and tables and it works great to see which user your are following, but the problem came when I tried to develop the Followers.

User_id  Following_id
1       2
1       3
1       4
1       6
2       4
2       6
  • User_ID=1 is following user: 2,3,4&6
  • User_ID=4 has followers: 1&2

How could I ask that table for the followers of user_id=4?

I thought that I should use a FollowerService and DAO, but I realized that I do not have a bean to use it. The only way I think I can do it is to fetch all the table and start searching for all the appearances of a certain following_id to see with user_id is the follower.

I can not find an easy way to do it. Do you think I should create a bean? How? Thanks

2 Answers

This was my solution for your problem. The user class:

@Entity
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    private String name;

    @OneToMany(mappedBy="to")
    private List<Followers> followers;

    @OneToMany(mappedBy="from")
    private List<Followers> following;

    public User() {}

    public User(String name) {
        this.name = name;
    }

}

As you can see the user class has a reference to the users who is following and those who he follows.

@Entity
public class Followers {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @ManyToOne
    @JoinColumn(name="from_user_fk")
    private User from;

    @ManyToOne
    @JoinColumn(name="to_user_fk")
    private User to;

    public Followers() {};

    public Followers(User from, User to) {
        this.from = from;
        this.to = to;
    }
}

The followers class contain the relationship between the two users, of course you might need to add more information to that class like when 'from' started following 'to'.

If you want to get the followers/following of a user you just call the respective getter.

Related