从JpaRepository方法返回一个布尔值

19

我在一个继承了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)
...

我尝试使用Spring repository和仅包含您查询的方法签名boolean。一切正常。您能否发布您的异常堆栈跟踪和实现。 - swinkler
@mh-dev 我尝试过 select 1select 'Y',但是两种情况都出现了 ClassCastException。 - Béla
返回类型应该是布尔型,但您能否发布整个异常信息? - mh-dev
@Béla:你能否发布ThingyServiceImpl(仓库类)和实体的内容。仅有堆栈跟踪而没有其他实现细节是没有帮助的。 - swinkler
@swinkler 添加为注释,因为老实说我看不出它的相关性。 - Béla
显示剩余7条评论
5个回答

14

我遇到了类似的问题。我的解决方案是使用java.lang.Boolean的投影。

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

希望这能对某人有所帮助。


这个方法的返回类型应该是布尔型吗? - Jordan Mackie
1
感谢 @JordanMackie 指出我的笔误。是的,返回类型应该是布尔型。我已经更新了我的解决方案。 - Gary
我的解决方案是 SELECT new java.lang.Boolean(count(rui) = 0) FROM table rui - Sham Fiorin

8

我认为您想要检查父ID的行是否存在,并根据此返回 true 和 false,然后进行案例

需要更改的查询内容。

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

这在不知道布尔值的愚蠢数据库上无法工作。Oracle: ORA-00904:“FALSE”无效标识符。 - ihebiheb
@ihebiheb 要么远离 Oracle(建议),要么编写 select case when exists (...) then 'Y' else 'N' end from dual 的代码。 - Bohemian

2
我测试了一下,去掉 true 周围的单引号可以正常工作。
@Query(nativeQuery = true, value = "select true from dual where exists("
      + "select * from child_table where parent_id = ?)")
String hasKids(long parentId);

3
你可能在使用一个带有布尔类型的数据库,例如Postgres?但我只能使用Oracle数据库,它不支持布尔类型。请问需要翻译其他内容吗? - Béla
@Béla,我很同情你不得不使用Oracle工作,但是你可以将查询编码为select case when exists (...) then 'Y' else 'N' end from dual - Bohemian
仍然无法使用Oracle和本地查询工作,“无法将字符串转换为布尔值”。没有引号:oracle.jdbc.OracleDatabaseException: ORA-00904:“N” - Tyvain

1

结合我使用的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);

-1

似乎有一个问题,至少在mysql中是这样 (count() >0) 在查询非本地化时可以转换为布尔值 (count() >0) 在查询本地化时返回“BigInteger cannot be cast to java.lang.Boolean”


这是作为问题的答案吗? - GrumpyCrouton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接