【问题标题】:Query output is throwing exception查询输出抛出异常
【发布时间】:2020-03-12 07:07:29
【问题描述】:

我正在使用休眠数据 jpa。这是我的仓库

公共接口 MappingRepository 扩展 JpaRepository (ConfigMapping, Long) {

@Query(value = "select count(machine_id) from machine_configuration where configuration_id =:Id and vm_machine_id =:vMId", nativeQuery = true)
public Long getCount(@Param("Id") Long Id, @Param("vMId") Long vMId);

现在在我的服务类中,当我尝试使用

获得结果时
for (int i = 0; i < vMList.size(); i++) {
     Long vMCount = vMRepo.getCount(Id, vMList.get(i));
   }

所以我总是遇到异常

com.sun.jdi.InvalidTypeException: generated value (java.math.Biginteger) is not compatible with declared type (java.lang.Long)

注意: vMList 是 VM 的列表,作为 List of Long

【问题讨论】:

  • 您是否尝试将“Long”的类型更改为“BigInteger”?
  • 是的,我试过了,但它的类型不匹配,说不能从 Long 转换为 BigInteger
  • select count() 返回一个 BigInteger,因为表中的行数可能非常多,因此计数可能大于 long 的最大值。因此,您必须接受这一点,并从您的方法中返回 BigInteger 而不是 Long。然后由您决定以您想要的方式使用返回的 BigInteger。如果您确信它的值适合 long,那么请阅读 BigInteger 的 javadoc 以了解如何将其转换为 long。

标签: java hibernate spring-data-jpa


【解决方案1】:

使用原始 long(不是包装对象 Long)。 请参阅示例 5. 中的派生计数查询 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts

【讨论】:

    【解决方案2】:

    实际上,我通过将 vMlist 更改为 BigInteger 而不是 Long 解决了这个问题。问题是,当它期望在 BigInteger 中时,我将 vm List 视为 Long。

    我还将 getCount() 方法更改为 BigInteger 而不是 Long。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 2011-10-17
      相关资源
      最近更新 更多