关于 Spring Data JPA 实现动态多条件查询

本文介绍如何使用Spring Data JPA实现动态多条件查询,包括Dao接口定义、Specification使用及其实现类代码示例,适合希望提高查询效率的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近抽出来一些时间来整理,最近用到的东西,这次主要是写一下 JPA 的动态实现多条件查询

这里就不贴全部的内容了,只贴出来了,关键代码

首先是 Dao,作为一个负责任的博主,我把引用的包也贴出来了,注意第一个 第二个 必须要有

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface XXXXDao extends JpaRepository<实体类的名字, String>, JpaSpecificationExecutor<实体类的名字>, PagingAndSortingRepository<实体类的名字, String> {
}

然后就是接口实现类,中间的过程就省略掉了例如什么什么Service 和 Controller,XXXServiceImpl 层 直接贴出代码了。。Ps 虽然我只想扔个图上去,深度懒癌患者,数据类型传过来的时候一定要是 Page<实体类名称> 类型

@Override
public Page<实体类名称> findAllPage(Pageable pageable,要传的参数 要传的参数) {
    //封装查询对象Specification  这是个自带的动态条件查询
    Specification<实体类名称> spec = new Specification<实体类名称>() {
        @Override
        public Predicate toPredicate(Root<实体类名称> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            //定义集合来确定Predicate[] 的长度,因为CriteriaBuilder的or方法需要传入的是断言数组
            List<Predicate> predicates = new ArrayList<Predicate>();
            //对客户端查询条件进行判断,并封装Predicate断言对象
            if(null != 要传的参数.getxxx()){
                predicates.add(criteriaBuilder.like(root.get("xxx"), "%"+要传的参数.getxxx()+"%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
    // 查询出全部数据源列表
    return xxxxDao.findAll(spec,pageable);
}

ServiceIpl 引用包。。。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平凡的人类

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值