繁体   English   中英

如何在Spring Boot Crud存储库中编写条件自定义查询

[英]How to write a Conditional Custom Query in Spring boot Crud Repository

我必须使用存储库从实体表中获取一条记录,该记录根据以下2个字段有条件地扩展了CRUDRepository。

有3个字段,分别是a,b和c。

SELECT from EntityClass e where e.a = :a AND

(e.b = :b and e.c = :c). If no record found, then it should try below one
(OR e.b = :b and e.c = null). If no record found, then it should try below one
(OR e.b = null and e.c = :c). If no record found, then it should try below one
(OR e.b = null and e.c = null).

肯定会有一个或多个记录与这四个条件中的任何一个相匹配。 但是我想要一条与任何条件匹配的记录,并且顺序从头到尾都很重要。

如何为此编写自定义查询?

@Query(" ")
EntityClass findEntityForAandBandC(@Param("a") String a, @Param("b") String b, @Param("c") String c);

我可以使用if else并编写单独的查询方法从Java代码执行此操作。 但是我想为上面的代码编写一个查询方法。

您可以使用JpaSpecificationExecutor<T>

EntityClassRepo

public class EntityClassRepo extends extends JpaRepository<Demo, Long>, 
                                             JpaSpecificationExecutor<Demo> {
}

所以现在您可以使用该方法

List< T > findAll(@Nullable Specification<T> spec)

  • findAll()采用Specificaion类,因此定义一个规范,您可以在其中动态提供条件

我不确定您需要什么查询,但是以下内容将为您提供一个思路。

EntityClassSpecificaiton(新类)

public class EntityClassSpecification implements Specification<EntityClass> {

    private EntityClassFilter entityFilter; // This holds the value A, B & C

    // Constructor 

    @Override
    public Predicate toPredicate(Root<Demo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
        if(/* Condition */) {
            return criteriaBuilder.equal(root.get("a"), entityFilter.getA());
        } else if (/* Condition */) {
            return criteriaBuilder.and(criteriaBuilder.equal(root.get("b"), entityFilter.getB()), criteriaBuilder.equal(root.get("c"), entityFilter.getC()));
        } else if (/* Condition */) {
            return criteriaBuilder.and(criteriaBuilder.equal(root.get("b"), entityFilter.getB()), criteriaBuilder.isNull(root.get("c")));
        } else if (/* Condition */) {
            return criteriaBuilder.and(criteriaBuilder.isNull(root.get("b")), criteriaBuilder.equal(root.get("c"), entityFilter.getC()));
        } else {
            return criteriaBuilder.and(criteriaBuilder.isNull(root.get("b")), criteriaBuilder.isNull(root.get("c")));
        }
    }
}

服务

public class EntityService {

   @Autowire
   private EntityClassRepo entityRepo;

   public List<EntityClass> getEntityClass(String a, String b, String c) {
      return entityRepo.findAll(new EntitySpecification(new EntityFilter(a, b, c)));
   }
}

您可以将自定义函数添加到存储库中。 您可以用Java代码实现自定义查询。

示例: https//dzone.com/articles/add-custom-functionality-to-a-spring-data-reposito

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM