美文网首页SpringBoot极简教程 · Spring Boot
Spring Data JPA 单表动态条件查询

Spring Data JPA 单表动态条件查询

作者: zhangweisep | 来源:发表于2020-03-17 15:01 被阅读0次

动态条件配置,使用泛型"T"作为实体类标识,在使用过程中替换成自己的实体类

/**
* 部分import引用
*/
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

public class MessageSpec {

    public static Specification<T> messageSpec(MessageJson messageJson){
            return new Specification<T>() {
                @Override
                public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> whereList = new ArrayList<>();
                    if(EmptyUtil.isNotEmpty(messageJson.getUserId())) {
                        whereList.add(cb.equal(root.get("userId"), messageJson.getUserId()));
                    }

                    whereList.add(cb.between(root.get("notificationTime"), messageJson.getStartTime(), messageJson.getEndTime()));
                    Predicate[] pre = new Predicate[whereList.size()];
                    return query.where(whereList.toArray(pre)).getRestriction();
                }
            };
        }
}

方法调用示例

Page<T> Messagepage = messageDao.findAll(MessageSpec.messageSpec(message),pageable);

pom.xml配置依赖

<!-- jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

相关文章

  • Spring Data JPA

    Spring Data JPA,一种动态条件查询的写法 我们在使用SpringData JPA框架时,进行条件查询...

  • Spring Data JPA 单表动态条件查询

    动态条件配置,使用泛型"T"作为实体类标识,在使用过程中替换成自己的实体类 方法调用示例 pom.xml配置依赖

  • 7 Spring-data-jpa查询方法

    springdata-jpa 八种查询方法 Spring Data JPA 简单查询--接口方法 jpa动态查询-...

  • JPA-复杂查询

    时间相关查询 Spring data jpa 条件查询-按时间段查询Jpa查询排序,时间范围查询,当天时间范围查询...

  • springboot jpa JpaSpecificationE

    示例一 Spring Data JPA之JpaSpecificationExecutor复杂动态查询实例 示例二 ...

  • 关于JPA中动态查询的做法

    原文出处: 【一目了然】Spring Data JPA使用Specification动态构建多表查询、复杂查询及排...

  • Example 查询

    Query By Example Spring Data JPA 实例查询

  • JPA查询

    jpa常用的查询方式 jpa官方文档 https://docs.spring.io/spring-data/jpa...

  • Spring Data JPA进阶

    Spring Data JPA进阶 目录 ddl属性配置 通过解析方法名查询 关联查询 spring.jpa.pr...

  • Spring Data JPA 动态条件查询+指定查询列

    JPA在使用(Specification的动态条件查询)时将不能指定查询列,这非常的操蛋,底层代码中封死了,必须返...

网友评论

    本文标题:Spring Data JPA 单表动态条件查询

    本文链接:https://www.haomeiwen.com/subject/rrjtyhtx.html