2

I use database query with JPA like that:

@Query("SELECT " + "new Report(" + "sum (r.fraction1)," + "sum (r.fraction2)) from Report r") Report calculateTotalReports(); 

When the database is full, it works fine, but when it is empty, the application crashes. How i can check when table contain rows and then select sum? I tried use CASE WHEN ... THEN, but JPA is not provide it.

Log of crashes:

QueryException: could not instantiate class [com.statistic.server.entity.Report] from tuple] with root cause

java.lang.IllegalArgumentException: null at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_201] at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_201] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~

3
  • Try using IFNULL or COALESCE Commented Feb 26, 2019 at 16:20
  • 1
    JPQL clearly does allow CASE statements, datanucleus.org:15080/products/accessplatform_5_2/jpa/… and saying an application crashes is likely down to the application. Posting the actual exception would tell you where it is crashing, because a JPA provider should not "crash" when there is no data. Commented Feb 26, 2019 at 16:20
  • If your constructor says Report(double, double) try changing it to Report(Double, Double) and maybe you'll be fine. Commented Feb 26, 2019 at 16:35

1 Answer 1

5

I guess you can use COALESCE in this case then it will return 0 if r.fraction1 is null.

 @Query("SELECT " + "new Report(" + "COALESCE(sum(r.fraction1),0)," + "COALESCE(sum(r.fraction2),0)) from Report r") 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.