首页 > 解决方案 > [Spring boot] 使用 join spring data jpa 进行本机查询时出错

问题描述

我在 Spring Boot 中与用户和角色有多对多的关系。我在数据库中有三个表(Role_utilisateur、users_roles 和 utilisateurs)。在我的存储库中,ireturn 名为 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] 的转换器

在此处输入图像描述

在此处输入图像描述

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

标签: javaspring-bootspring-data-jpaspring-repositories

解决方案


The problem is you're selecting two columns and returning a list of entities. You need to either select the entity in your query or return the list of two values in a collection.

To return entities you would need to convert your query to JPQL. The following is a JPQL representation of your native query. I've had to do some guessing for the joins (I assume you have some JPA related entities):

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

If you go the native query route:

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

The returned list should yield:

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

}


推荐阅读