简体   繁体   中英

JPA check if null query

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM