Béla
Béla

Reputation: 284

Return a boolean from a JpaRepository method

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)
...

Upvotes: 19

Views: 35980

Answers (4)

LethalLima
LethalLima

Reputation: 231

With my Oracle constraint and a combination of all the suggestions here, I found a solution that worked for my situation without having to call 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);

Upvotes: 2

Gary
Gary

Reputation: 143

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.

Upvotes: 14

Ashwani Tiwari
Ashwani Tiwari

Reputation: 1567

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.

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 = ?)

Upvotes: 8

Kamron Batman
Kamron Batman

Reputation: 56

I tested this by removing the single quotes around true and it works.

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

Upvotes: 2

Related Questions