Spring Data Jpa多对多查询

时间:2016-02-22 02:01:56

标签: jpa spring-data-jpa

实体:

 Class User{
    private String id;
    @ManyToMany
    private List<Role> roles;
 }

 Class Role{
   private String id;
   @ManyToMany(mappedBy = "roles")
   private List<User> users; 

 }

UserRepository:

 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()方法获取The Role对象),@ query怎么写 (不是@Transactional,)

1 个答案:

答案 0 :(得分:0)

manyToMany的默认提取类型是Lazy。 所以为了获得角色列表,你需要做两个中的一个: 1.在事务中执行configure方法。 2.设置与EAGER获取类型的关系:

[
  {"First chapter", "Lorem ipsum dolor sit amet, consetetur sadipscing elitr."},
  {"Second chapter", "Sed diam nonumy eirmod tempor invidunt ut labore et."},
  {"Third chapter", "Dolore magna aliquyam erat, sed diam voluptua."}
]