Spring Data JPA 使用 Exists 查询的一点发现

新项目有点乱,操作数据库的代码有原生 Mybatis、Mybatis-Plus,竟然还有使用 Spring Data JPA。刚看代码发现使用 JPA Exists 判断数据库中对象是否存在时,可以用两种写法实现。

比如,我们经常看到的写法

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

但还可以这样写,也是能查询成功。

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsMyEntityByFoo(String foo);
}

查询两个字段,比较是否存在就这样写

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsMyEntityByIdAndFoo(int id,String foo);
}

一篇水文,主要花了我一点时间测试,所以记录在这,希望能帮到也有此疑惑的朋友。

本文由老郭种树原创,转载请注明:https://guozh.net/spring-data-jpa-uses-exists-queries-for-a-little-discovery/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注