【发布时间】:2016-06-03 08:23:45
【问题描述】:
实体:
Class User{
private String id;
@ManyToMany
private List<Role> roles;
}
Class Role{
private String id;
@ManyToMany(mappedBy = "roles")
private List<User> users;
}
用户存储库:
public interface UserRepository extends PagingAndSortingRepository<User, Serializable>{
@Query(" ??? ")
public User getUser(String id);
}
public class InMemorySecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(username -> {
com.casnetvi.cloud.domain.login.User employee = userRepository.findByEmail(username);
if (employee == null) {
throw new BadCredentialsException("User not found");
}
List<Role> roles1 = employee.getRoles();
System.out.println(roles1);
发生打印异常:
未能延迟初始化角色集合:com.casnetvi.cloud.domain.login.User.roles,无法初始化代理 - 无会话”
想知道是什么角色(使用getRoles()方法获取角色对象),@Query怎么写 (不是@Transactional,)
【问题讨论】:
-
您可以尝试使用
@Query("select u from User u left join fetch u.roles where u.id=:id")并在方法签名之前添加@Param("id")为getUser(@Param("id") String id) -
如果参数名称相同,则不需要添加@Param。此外,这里没有对错,但我会考虑添加某种类型的第三个表 UserRole 并在那里关联用户和角色。我相信这会让您未来的生活更轻松。
-
@MadhusudanaReddySunnapu,我应该看看 JPQL 查询,非常感谢
-
@Desorder,你的意见很有用,我试试做个Demo,谢谢
标签: jpa spring-data-jpa