zak*_*zak 2 java spring 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<>();
}
Run Code Online (Sandbox Code Playgroud)
每个用户可以有多个角色。给定一个角色(以字符串数据类型表示),我想获取具有该角色的所有用户。
例如
用户 1 的角色:“admin”
User2 角色:“user”
User3 角色:“admin”
对于角色“admin”,我想得到 User1 和 User2 的结果。
我对 Spring Data Jpa 的尝试:
public interface UserRepository extends JpaRepository<User, Integer> {
public List<User> findByRoles( String role);
}
Run Code Online (Sandbox Code Playgroud)
但我得到了例外
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);
}
Run Code Online (Sandbox Code Playgroud)
在你的控制器中
@GetMapping(value = "/api/usersByRole/{userRole}")
public List<User> getUser(@PathVariable String userRole, Pageable pageable){
return userRepository.findByRolesIn(Arrays.asList(userRole), pageable);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11139 次 |
| 最近记录: |