【问题标题】:Spring Data Jpa Many to Many QuerySpring Data Jpa 多对多查询
【发布时间】: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


【解决方案1】:

manyToMany 的默认获取类型是 Lazy。 因此,为了获得角色列表,您需要执行以下两项之一: 1. 在事务中执行配置方法。 2.设置与EAGER fetch type的关系:

@ManyToMany(fetch=FetchType.EAGER)
private List<Role> roles;

【讨论】:

  • 使用@JsonManagedReference 防止JSON无限循环,fetch 不起作用
猜你喜欢
  • 2016-01-31
  • 2018-10-31
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2015-05-10
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多