【问题标题】:Find user by role using spring data jpa使用spring data jpa按角色查找用户
【发布时间】:2019-11-20 05:07:53
【问题描述】:

我的用户实体

@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<>();
}

每个用户都可以有多个角色。给定一个角色(以字符串数据类型表示),我想获取所有具有该角色的用户。

例如

角色为“admin”的用户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.certificate.securityconfig.User.roles,不能 初始化代理 - 没有会话

【问题讨论】:

  • 从您提到的讨论中,我选择了要求从 List 更改为 Set 的解决方案。它工作正常。但是为什么,其他讨论没有解释。
  • 一定是阅读了与我不同的讨论。
  • 您能否提及解释为什么 Set 对列表起作用的部分。我不是在谈论例外的原因。谢谢
  • 可能没有——你没有示例和编辑。

标签: java spring spring-data-jpa


【解决方案1】:

在你的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);
}

你会得到这样的结果

【讨论】:

    【解决方案2】:

    这里从用户角色一对多映射
    即角色列表是的一个元素用户 实体,并且您将 String 作为角色列表传递。
    这就是您获得异常的原因。

    解决方案:

    • 使用findByRolesIn(List&lt;String&gt; roles) 而不是findByRoles(String role)
    • 或者,如下进行一对一映射:

      @Column(nullable = false)
      private String role;
      
    • 或者,使用 JPA 查询或本机查询,如下所示。

      @Query( "select u from User u  where u.roles in :roles" )
      public List<User> findByRoles(@Param("roles") List<String> roles);
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2019-02-06
      • 2020-10-09
      • 2020-10-13
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多