首页 > 解决方案 > 使用spring data jpa按角色查找用户

问题描述

我的用户实体

@Entity
public class User {

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

    @Column(nullable = false)
    private String username;

    @Column(nullable = false)
    private String password;

    @ElementCollection
    private List<String> roles = new ArrayList<>();
}

每个用户可以有许多角色。给定一个角色(以字符串数据类型表示),我想获取所有具有此角色的用户。

例如

具有角色的用户 1:“管理员”

具有角色的用户 2:“用户”

具有角色的用户 3:“管理员”

对于角色“管理员”,我想得到 User1 和 User2。

我对 Spring Data Jpa 的尝试:

public interface UserRepository extends JpaRepository<User, Integer> {
    public List<User> findByRoles( String role);
}

但我得到了一个例外

org.hibernate.LazyInitializationException:无法延迟初始化角色集合:com.spring.certificatie.securityconfig.User.roles,无法初始化代理 - 没有会话

标签: javaspringspring-data-jpa

解决方案


在你的 UserRepository 中以这种方式使用

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);
}

在你的控制器中

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

你会有这样的结果 在此处输入图像描述


推荐阅读