SpringBoot+hibernate,实现多参数查询

po

实体类NewsQuery存储查询参数

package com.gitee.xvyihj.po;

public class NewsQuery {
    private String title;
    private String typeId;
    private Boolean recommend;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTypeId() {
        return typeId;
    }

    public void setTypeId(String typeId) {
        this.typeId = typeId;
    }

    public Boolean getRecommend() {
        return recommend;
    }

    public void setRecommend(Boolean recommend) {
        this.recommend = recommend;
    }

    @Override
    public String toString() {
        return "NewsQuery{" +
                "title='" + title + '\'' +
                ", typeId='" + typeId + '\'' +
                ", recommend=" + recommend +
                '}';
    }
}

dao

INewDao继承JpaSpecificationExecutor< News>

package com.gitee.xvyihj.dao;

import com.gitee.xvyihj.po.News;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface INewsDao extends JpaRepository<News,Long>, JpaSpecificationExecutor<News>
{
}

service

NewsService拼接查询参数

    @Override
    public Page<News> searchNews(Pageable pageable, NewsQuery newsQuery) {
        Page<News> news=newsDao.findAll(new Specification<News>()
        {
            @Override
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                if(!StringUtils.isEmpty(newsQuery.getTitle()))
                {
                    predicates.add(criteriaBuilder.like(root.<String>get("title"),"%"+newsQuery.getTitle()+"%"));
                }
                if(!StringUtils.isEmpty(newsQuery.getTypeId()))
                {
                    predicates.add(criteriaBuilder.equal(root.<Type>get("type").get("id"),newsQuery.getTypeId()));
                }
                if(newsQuery.getRecommend()!=null)
                {
                    predicates.add(criteriaBuilder.equal(root.<Boolean>get("recommend"),newsQuery.getRecommend()));
                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
        return news;
    }

controller

NewsControll查询

    @RequestMapping("search")
    public String search(@PageableDefault(size = 5,sort={"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
                         NewsQuery newsQuery,
                         Model model){
        Page<News> page=newService.searchNews(pageable,newsQuery);
        model.addAttribute("page",page);
        return "admin/news :: newsList";
    }
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页