【问题标题】:Select field from table with @Query using Spring Boot JPARepository使用 Spring Boot JPARepository 从带有@Query 的表中选择字段
【发布时间】:2022-11-03 00:36:49
【问题描述】:

是否可以从表中选择一个或多个字段并将其映射到实体中?

目前正在尝试

@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{  
    @Query("SELECT r.roleId, r.name FROM role r")  
    List<Role> getAllRoleNames();
}

我只想要这 2 个值,其余字段可以是 null 以提高效率。我现在得到的错误是

ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role] for value '{1, Java Dev}'; 
nested exception is org.springframework.core.convert.ConverterNotFoundException: 
No converter found capable of converting from type [java.lang.Long] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role]] with root cause

那么,当我不能只说object.Id = role.roleIdobject.Id 就是1)时,我该如何进行转换。

【问题讨论】:

    标签: java spring spring-boot jpa


    【解决方案1】:

    请参阅“使用聚合函数自定义 JPA 查询的结果”中的 Customizing the Result With Class Constructors

    @Repository
    public interface RoleRepo extends JpaRepository<Role, Long>{  
        @Query("SELECT new demo.model.Role(r.roleId, r.name) FROM role r")  
        List<Role> getAllRoleNames();
    }
    

    Role 类中必须存在适当的构造函数。

    【讨论】:

      猜你喜欢
      • 2019-08-21
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 2020-03-09
      相关资源
      最近更新 更多