Spring数据CrudRepository存在 [英] Spring data CrudRepository exists

查看:71
本文介绍了Spring数据CrudRepository存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我扩展CrudRepository接口时,我的子界面中有exists(ID)方法.我可以写findBy<property>方法.

When I extend CrudRepository interface, I have exists(ID) method in my subinteface. I can write findBy<property> methods.

是否可能以某种方式编写将返回booleanexistBy<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存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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