簡體   English   中英

從 JpaRepository 方法返回一個布爾值

[英]Return a boolean from a JpaRepository method

我在擴展JpaRepository的接口中有一個本機查詢。 理想情況下,該方法應該返回一個布爾值,但我不知道如何選擇任何自動轉換為boolean

這有效,盡管我必須將其稱為Boolean.valueOf(hasKids(id))

// yuck. I wanted a boolean
@Query(nativeQuery = true, value = "select 'true' from dual where exists("
          + "select * from child_table where parent_id = ?)")
String hasKids(long parentId);

如何將其更改為更自然的返回類型?

boolean hasKids(long parentId);  // throws ClassCastException

更新:

恕我直言,堆棧跟蹤不是很有幫助,因為它是 Hibernate 代理和 AspectJ 閉包的常見噩夢,但無論如何這里是相關部分。

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
    at com.sun.proxy.$Proxy1025.hasKids(Unknown Source)
    at com.bela.foo.bar.Service.ThingyServiceImpl.recordHasKids_aroundBody4(ThingyServiceImpl.java:85)
    at com.bela.foo.bar.Service.ThingyServiceImpl$AjcClosure5.run(ThingyServiceImpl.java:1)
...

我遇到了類似的問題。 我的解決方案是使用 java.lang.Boolean 的投影。

@Query("select new java.lang.Boolean(count(*) > 0) from child_table where parent_id = ?")
Boolean hasKids(long parentId);

希望這可以幫助某人。

我認為您想檢查父 id 的行是否存在,並在此基礎上返回 true 和 false,然后進行case

查詢中所做的更改

    "select case when (count(*) >0) then true else false end from dual where exists("
      + "select * from child_table where parent_id = ?)

我通過刪除 true 周圍的單引號來測試它並且它有效。

@Query(nativeQuery = true, value = "select true from dual where exists("
      + "select * from child_table where parent_id = ?)")
String hasKids(long parentId);

使用我的 Oracle 約束和這里所有建議的組合,我找到了一個解決方案,無需調用 Boolean.valueOf(hasKids(id)) 即可滿足我的情況:

@Query(nativeQuery = true, value = "select case when exists(select * from child_table " 
    + "where parent_id = :parentId) then 'true' else 'false' end from dual")
Boolean hasKids(@Param("parentId") long parentId);

實際上查詢應該是這樣的:

@Query("SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END FROM User u WHERE rs = :user")
    boolean userExsist(@Param("user") User user);

當然,像上面這樣的示例僅在您想要運行自定義查詢時才有效。

似乎有一個問題,至少當查詢是非本地查詢時,mysql (count( ) >0) 轉換為布爾值很好 (count( ) >0) 返回“BigInteger cannot be cast to java.lang.Boolean”當查詢是原生的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM