Home > Enterprise >  Displaying only members who belong to a certain team in Spring
Displaying only members who belong to a certain team in Spring

Time:11-30

I am trying to update my Spring / React webapp to have different teams and when a user looks at their team, only members of that team are displayed.

So far I have a Society entity with a @OneToMany relationship with User

User
@ManyToOne
    @JoinColumn(name = "society_id")
    private Society society;

-------------------------------------
Society
@JsonIgnore
    @OneToMany(mappedBy = "society")
    private List<User> users;

I have implemented so that when a new user is created they are assigned to the society that the person who created them is in.

I am not trying to implement so that when I make my call from React to Spring to get a Page of users, it returns only the Users who are in the same society as the person who made the request.

So far, I have tried add the society_id of the person who made the call to the request path,

in React,

export const listUsers = (param = { page: 0, size: 9 }) => {
  const path = url   `/api/1.0/users/${id}?page=${param.page || 0}&size=${param.size || 9}&sort=username,asc`;
  return axios.get(path);
};

in Spring controller

//Get page of members
    @CrossOrigin
    @GetMapping("/users/{id:[0-9] }")
    Page<UserVM> getUsers(Pageable page, long id) {
        return userService.getUsers(page, id).map(UserVM::new);
    }

//In userSerice

public Page<User> getUsers(Pageable pageable, long id) {

        return userRepository.findAllBySociety(pageable, id);
    }

//In userRepository

@Query(value = "select u from User u Where society_id=:id")
    Page<User> findAllUsers(Pageable page, long id);

This is giving an error though as I think it is trying to pass the value of id as a Society which it doesn't like.

Could anyone help solve how I get around this or if there is going to be a better way to get a list of User for the society that the logged-in user is part of.

CodePudding user response:

Assuming that your Society entity has an id property, the following method in your Repository should work (the corresponding query will be generated by Spring Data JPA):

public Page<User> findAllBySocietyId(Pageable page, long id);

Then you just need to call it in your Service:

public Page<User> getUsers(Pageable pageable, long id) {
    return userRepository.findAllBySocietyId(pageable, id);
}
  • Related