春季数据jpa.如果没有结果返回默认值,则查找最大值 [英] Spring data jpa. Find max if no result return default value

查看:778
本文介绍了春季数据jpa.如果没有结果返回默认值,则查找最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在自己的Spring存储库界面中实现了

I've implemented in my spring repository interface:

@Query("SELECT max(ch.id) FROM MyEntity ch")
Long getMaxId();

如果db不为空,它将正常工作.如果我以测试配置启动环境(使用H2DB),则一开始就没有数据.并且getMaxId()返回的结果为.我想在这里 0 .

It works correctly if db is not empty. If I start my environment with test configuration (H2DB is used) - there is no data in the very beginning. And result returned by getMaxId() is null. I would like to have here 0.

是否可以将我的*JpaRepository修改为具有 0 的结果?如果是,应该如何修改?

Is it possible to modify my *JpaRepository to have 0 result? If yes, how it should be modified?

推荐答案

您可以像这样使用coalesce:

@Query("SELECT coalesce(max(ch.id), 0) FROM MyEntity ch")
Long getMaxId();

如果没有数据,它将返回0而不是null.

If there are no data it will return 0 instead of null.

这篇关于春季数据jpa.如果没有结果返回默认值,则查找最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆