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
.
This works, although I have to call it as 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.
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)
...
It's a boolean result of an evaluation - true or false . If it's true, do something. Using it with return returns that boolean result to the caller.
JpaRepository. JpaRepository is particularly a JPA specific extension for Repository. It has full API CrudRepository and PagingAndSortingRepository. So, basically, Jpa Repository contains the APIs for basic CRUD operations, the APIS for pagination, and the APIs for sorting.
Did you know that you can return a boolean value from a Spring Data JPA query? For instance, you may want to know whether or not an entity (i.e. database row) exists with a given value for a field.
The boolean method returns true if it is even and false when it is odd. In the code above, the first step is to declare the boolean method and the return value expected. The boolean method returns a value that guides how the code login is implemented in the next method.
public: this is a modifier that shows that the class, field, method, and constructor can be accessed by all codes regardless of the location. boolean: This identifies the type of value expected to return after the method performs the specified tasks. checkPassword (): This the name of the method.
A default JpaRepository can be used for the following purposes: Bring a specific coin by id . . . In addition to the previous ones, by defining a simple method; the followings can be performed by implementing a JpaRepository: Bring all coins sorted by an attribute (i.e. name)
I ran into a similar problem. My solution was to use a projection of 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With