skip to Main Content

I am trying to develop a social network in Angular and Spring.

I have users and they can follow eachother.
My User class looks something like this.

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @OneToMany(mappedBy = "following")
    private List<Follow> followers;

    @OneToMany(mappedBy = "follower")
    private List<Follow> following;

}

Is there anyway I can get all the users ordered by the number of followers?

2

Answers


  1. In your UserRepository you could try the following…

    @Query("select u from User u order by u.followers.size")
    User findAllOrderedByFollowing();
    

    Taking full advantage of JPA. Hope this helps.

    Login or Signup to reply.
  2. I have definitely done this in MySQL; I don’t have the query where I did this right on hand though.

    I think it is something like

    select id, count(followers) as indx from ..., collate by id, order by indx
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search