Find user by role using spring data jpa

后端 未结 2 1624
忘掉有多难
忘掉有多难 2021-01-28 10:51

My User Entity

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = fals         


        
相关标签:
2条回答
  • 2021-01-28 11:16

    Here from User to Role is ONE-TO-MANY mapping
    i.e list of Roles is an element of User entity, and you are passing a String as List of Roles.
    This is the reason you are getting Exception.

    Solutions:

    • Use findByRolesIn(List<String> roles) instead of findByRoles(String role)
    • Or, Make one-to-one mapping as below:

      @Column(nullable = false)
      private String role;
      
    • Or, Use JPA Query or Native query as below.

      @Query( "select u from User u  where u.roles in :roles" )
      public List<User> findByRoles(@Param("roles") List<String> roles);
      
    0 讨论(0)
  • 2021-01-28 11:31

    In your UserRepository use in this way

    import org.springframework.data.jpa.repository.JpaRepository;
    
    import java.util.Collection;
    import java.util.List;
    
    public interface UserRepository extends JpaRepository<User, Long> {
        List<User> findByRolesIn(Collection<String> names, Pageable pageable);
    }
    

    In your Controller

    @GetMapping(value = "/api/usersByRole/{userRole}")
    public List<User> getUser(@PathVariable String userRole, Pageable pageable){
        return userRepository.findByRolesIn(Arrays.asList(userRole), pageable);
    }
    

    And You will have result like this

    0 讨论(0)
提交回复
热议问题