[Spring boot] 使用join spring data jpa

问题描述

我在 Spring Boot 中与用户和角色之间存在多对多关系。我在数据库中有三个表(Role_utilisateur、users_roles 和 utilisateurs)。在我的存储库中,我返回了名为 RoleEntite 的实体列表,它具有两个属性(nom 和 id)。

@Query(value = "SELECT ROLE_UTILISATEUR.NOM,ROLE_UTILISATEUR.ROLE_ID " + "FROM ROLE_UTILISATEUR "
            + "INNER JOIN USERS_ROLES on users_roles.role_id = ROLE_UTILISATEUR.ROLE_ID "
            + "INNER JOIN UTILISATEURS on utilisateurs.utilisateur_id = USERS_ROLES.UTILISATEUR_ID "
            + "WHERE UTILISATEURS.UTILISATEUR_ID = :userId",nativeQuery = true)
    List<RoleEntite> findUsersRolesNative(@Param("userId") Long userId);

当我调用我的函数

private List<GrantedAuthority> getGrantedAuthorities(UserEntite user) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        List<RoleEntite> roleList = userRepository.findUsersRolesNative(user.getId());
        for (RoleEntite roleEntite : roleList) {
            authorities.add(new SimpleGrantedAuthority(roleEntite.getNom()));
        }
        return authorities;
    }

我在 java eclipse 中遇到这个错误

org.springframework.security.authentication.InternalAuthenticationServiceException:无法从类型 [java.lang.Object[]] 转换为类型 [com.id.firstSpringBoot.entite.RoleEntite] 的值“{ADMIN,1” }';嵌套异常是 org.springframework.core.convert.ConverterNotFoundException:找不到能够从 [java.lang.String] 类型转换为 [com.id.firstSpringBoot.entite.RoleEntite] 类型的转换器

enter image description here

enter image description here

我如何解决这个错误并在我的函数 getGrantedAuthorities 中获取名称 ADMIN 可以做到这一点

解决方法

问题是您要选择两列并返回实体列表。您需要选择查询中的实体或返回集合中包含两个值的列表。

要返回实体,您需要将查询转换为 JPQL。以下是您的本机查询的 JPQL 表示。 我不得不对连接进行一些猜测(我假设您有一些与 JPA 相关的实体):

@Query(value = "SELECT RoleEntite r "
        + "INNER JOIN UserRole r.user u "
        + "INNER JOIN Utilisateurs u.Utilisateur x "
        + "WHERE x.UTILISATEUR_ID = :userId")
List<RoleEntite> findUsersRolesNative(@Param("userId") Long userId);

如果你走原生查询路线:

@Query(value = "SELECT ROLE_UTILISATEUR.NOM,ROLE_UTILISATEUR.ROLE_ID " + "FROM ROLE_UTILISATEUR "
        + "INNER JOIN USERS_ROLES on users_roles.role_id = ROLE_UTILISATEUR.ROLE_ID "
        + "INNER JOIN UTILISATEURS on utilisateurs.utilisateur_id = USERS_ROLES.UTILISATEUR_ID "
        + "WHERE UTILISATEURS.UTILISATEUR_ID = :userId",nativeQuery = true)
List<Object[]> findUsersRolesNative(@Param("userId") Long userId);

返回的列表应该产生:

for (Object[] obj : list) {
 nom = obj[0];
 roleId = obj[1];
 // ... do what ever you want with the values

}