java 从 JpaRepository 方法返回一个布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30182383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return a boolean from a JpaRepository method
提问by Béla
I have a native query in an interface which extends JpaRepository
. The method should ideally return a boolean value, but I can't figure out how to SELECT anything that gets automatically translated into boolean
.
我在扩展JpaRepository
. 理想情况下,该方法应该返回一个布尔值,但我不知道如何选择任何自动转换为boolean
.
This works, although I have to call it as Boolean.valueOf(hasKids(id))
:
这有效,尽管我必须将其称为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);
How can I change this to the more natural return type?
如何将其更改为更自然的返回类型?
boolean hasKids(long parentId); // throws ClassCastException
Update:
更新:
the stacktrace is not very helpful IMHO because it's the usual nightmare of Hibernate proxies and AspectJ closures, but here's the relevant portion anyway.
恕我直言,堆栈跟踪不是很有帮助,因为它是 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)
...
回答by Ashwani Tiwari
I think you want to check the row exist or not for the parent id,and return true and false on the basis of that, then go for the case.
我认为您想检查父 id 的行是否存在,并在此基础上返回 true 和 false,然后进行case。
Changes to made in query
查询中所做的更改
"select case when (count(*) >0) then true else false end from dual where exists("
+ "select * from child_table where parent_id = ?)
回答by Gary
I ran into a similar problem. My solution was to use a projection of java.lang.Boolean.
我遇到了类似的问题。我的解决方案是使用 java.lang.Boolean 的投影。
@Query("select new java.lang.Boolean(count(*) > 0) from child_table where parent_id = ?")
Boolean hasKids(long parentId);
Hope this helps someone.
希望这可以帮助某人。
回答by Kamron Batman
I tested this by removing the single quotes around true and it works.
我通过删除 true 周围的单引号来测试它并且它有效。
@Query(nativeQuery = true, value = "select true from dual where exists("
+ "select * from child_table where parent_id = ?)")
String hasKids(long parentId);
回答by John Windberg
There seems to be an issue, at least with mysql (count() >0) convert to boolean fine when the query is non native (count() >0) returns a "BigInteger cannot be cast to java.lang.Boolean" when the query is native
似乎有一个问题,至少当查询是非本地查询时,mysql (count( ) >0) 转换为布尔值很好 (count() >0) 返回“BigInteger cannot be cast to java.lang.Boolean”当查询是原生的