I have select max code from my table it work when it have data but when table is empty i got error as bellow:
Here is may code in Repository:
@Repository("depositRepository")
public interface DepositRepository extends JpaRepository<Deposit,Integer>,
JpaSpecificationExecutor<Deposit> {
@Query("select max(u.code) from Deposit u")
String getMaxCode();
}
And here is code i call in service for get result:
String maxCode=depositRepo.getMaxCode();
I got error as i have mentioned below:
Hibernate:
select
max(deposit0_.code) as col_0_0_
from
rems.tbldeposit deposit0_
20:10:55,182 ERROR [rems.controller.DepositController] java.lang.NullPointerException
The DBMS returns null when selecting a max() from an empty record set.
It's hard to tell without seeing more code context from your service method, but I'm guessing you're later calling some operation on the getMaxCode() result, like maxCode.equals(...) or maxCode.toString(), which gives you a NullPointerException.
To avoid the exception, you can either do a null check in your java code:
String maxCode=depositRepo.getMaxCode();
maxCode = (maxCode==null) ? "0" : maxCode;
or you can tweak the query to return a default value in the event max(u.code) is null, like this:
@Query("select coalesce(max(u.code), '0') from Deposit u")
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