java - 使用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,无法初始化代理 - 没有会话
解决方案
在你的 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);
}
推荐阅读
- javascript - 使用变量在组件中设置样式背景图像
- arrays - Python:附加一个列表,其中包含在函数中评估为真的元素
- javascript - 使用 JavaScript 从每个元素中删除隐藏类
- flutter - 如何在 Flutter 中设置默认选中的单选按钮?
- java - 使用自定义 JDBC 驱动程序与使用 HTTP 通信的 Zuul-Eureka Spring-Boot 应用程序一起工作时出现问题
- powershell - PowerShell脚本使用数组检查文件/文件夹是否存在
- sql - 查找低于子集 min() 的集合的所有值
- database - 数据建模 Microsoft Office
- rest - Meteor simple:rest 包不认天文包方法
- c# - 无法将带有 [] 的索引应用于“int”类型的表达式