java - [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 可以做到这一点
解决方案
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
}
推荐阅读
- c - 带负数的 imul dx 在 EAX 中产生大的正数?
- python - 用逗号拆分以及如何在python中拆分引号中排除逗号
- ruby-on-rails - 是否有可能 Rails 声明 gem 应该自动更新?
- sql-server - 使用网络文件和/或远程 SQL Server 的 ssis 包涉及哪些跃点?
- php - 如何在 WP_Query 中合并 2 个数据数组?- WordPress
- image - 图像标签,如何注释没有对象但我应该有它的 xml 文件的图片,正如我在问题中解释的那样
- javascript - 如何修复超时溢出警告?
- android - 在 Android 10 中,图像 URI 中的文件路径并未真正检索到
- java - 如何根据收到的参数模拟从数据库返回的对象?
- typescript - Redux 持续存在问题 - 状态未保存在本地