spring data jpa 动态查询(mysql)

Posted lshan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring data jpa 动态查询(mysql)相关的知识,希望对你有一定的参考价值。

cankao : https://stackoverflow.com/questions/45973070/spring-jpa-examplematcher-compare-date-condition

场景: 动态条件查询, (主要解决时间问题)

repository

public interface TranxlogRepository extends JpaRepository<Tranxlog, Long>, JpaSpecificationExecutor<Tranxlog>{ 
}

 

serviceImp:

public Specification<TranxLog> getSpecFromDatesAndExample(
  LocalDateTime from, LocalDateTime to, Example<TranxLog> example) {

    return (Specification<TranxLog>) (root, query, builder) -> {
         final List<Predicate> predicates = new ArrayList<>();

         if (from != null) {
            predicates.add(builder.greaterThan(root.get("dateField"), from));
         }
         if (to != null) {
            predicates.add(builder.lessThan(root.get("dateField"), to));
         }
         predicates.add(QueryByExamplePredicateBuilder.getPredicate(root, builder, example));

         return builder.and(predicates.toArray(new Predicate[predicates.size()]));
    }
};

..

public Page<TranxLog> findAllByConditions(TranxReportFormModel formModel, Pageable page) {
    ExampleMatcher matcher = ExampleMatcher.matching()
            .withNullHandler(ExampleMatcher.NullHandler.IGNORE)
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
            .withIgnoreCase()
            .withIgnoreNullValues();
    Example<TranxLog> example = Example.of(formModel.getTranxLog(), matcher);
    return tranxlogRepository.findAll(getSpecFromDatesAndExample(from, to, Example.of(formModel.getTranxLog(), matcher)), page);
}

 

以上是关于spring data jpa 动态查询(mysql)的主要内容,如果未能解决你的问题,请参考以下文章

spring data jpa 动态查询(mysql)

spring data jpa 动态查询(mysql)

请教关于Spring Data JPA动态查询参数的问题

Spring Data JPA 的 Specifications动态查询

spring-data-jpa动态条件查询

Spring Data JPA动态查询(多条件and)