如何从具有外键类型的jpa存储库返回选择查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从具有外键类型的jpa存储库返回选择查询相关的知识,希望对你有一定的参考价值。

我想这样做:

@Query(value = "SELECT DISTINCT c.* FROM comarca c INNER JOIN debito_negativacao d ON d.comarca_id = c.id WHERE d.status = :status", nativeQuery = true)
List<Comarca> findDistinctComarcaByStatus(@Param("status") String status);

但我得到这个错误:

  org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type [com.hc.projects.model.Comarca] for value '{9, 0, 7323}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.math.BigInteger] to type [com.hc.projects.model.Comarca]
答案

如果您想第二次隔离comarca_id列表,请尝试流式传输您的请求结果。

    List<Comarca> comarca = debitoNegativacao.stream().map(dn -> dn.getComarca()).distinct().collect(Collectors.toList());

++

另一答案

您必须返回构建Comarca所需的所有列。所以你必须加入这个表。

由于没有提供表格,我只能猜测:

@Query(value = "SELECT DISTINCT * FROM comarca c " +
                "JOIN debito_negativacao d ON d.comarca_id = c.id "+
                "WHERE d.debito_negativacao.status= :status", nativeQuery = true)
List<Comarca> findDistinctComarcaIdByStatus(@Param("status") String status);
另一答案

您的请求告诉您需要一个BigInteger列表:SELECT DISTINCT comarca_id ...因为我猜comarca_id是一个大整数。如果您想要Comarca列表,则必须在所有桌面上提出要求。

另一答案

如果你想使用一个独特的查询来返回除了不同列之外的其他列,你需要某种策略来“合并”这些对象。想象一下这样的行:

------------------------------
| comarca_id| key | status    |
| 1         | A   | your_state|
| 1         | B   | your_state|
| 2         | C   | your_state|
------------------------------

在这种情况下你会得到什么?

SELECT DISTINCT comarca_id FROM comarca;将返回1,2

但是,如何合并两个(或更多)具有相同comarca_idand status的条目?

这让你有三种情况:

  1. 你假设comarca_id + status是独一无二的 - >你不需要DISTINCT查询
  2. 可能有多个行具有相同的comarca_idstatus - >您无法使查询明显
  3. 你只想要不同的comarca_id值 - >让你的方法返回List<BigInteger>

以上是关于如何从具有外键类型的jpa存储库返回选择查询的主要内容,如果未能解决你的问题,请参考以下文章