问题描述
当我扩展CrudRepository
接口时,我的子界面中有exists(ID)
方法.我可以写findBy<property>
方法.
When I extend CrudRepository
interface, I have exists(ID)
method in my subinteface. I can write findBy<property>
methods.
是否可能以某种方式编写将返回boolean
的existBy<property>
方法.或使用@Query(jpa query)
对其进行注释,以使其返回boolean
.
Is it possible somehow to write existBy<property>
method that will return boolean
. Or to annotate it with @Query(jpa query)
so it will return boolean
.
我知道我可以执行select count(*)
并返回long
,但是随后我将不得不在服务层中执行!=0
校验.
I know that I can do select count(*)
and return long
, but then I will have to do !=0
check in my service layer.
推荐答案
@Oleksandr的答案是正确的,但是我可以使它起作用的唯一方法如下.我在PostgreSQL上使用Eclipselink.
@Oleksandr's answer is correct, but the only way I could get it to work is as follows. I'm using Eclipselink on PostgreSQL.
public interface UserRepository extends JpaRepository<User, Long>
{
@Query("SELECT CASE WHEN COUNT(u) > 0 THEN 'true' ELSE 'false' END FROM User u WHERE u.username = ?1")
public Boolean existsByUsername(String username);
}
这篇关于Spring数据CrudRepository存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!