SpringDataJPA中使用Specification进行表连接多条件分页动态查询

导读:本篇文章讲解 SpringDataJPA中使用Specification进行表连接多条件分页动态查询,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一直使用springboot开发,很久没用过jpa了,最近公司的项目用jpa,这就用到了Specification进行多表连接多条件动态查询,想了想还是简单的总结一下。废话不多说,具体实现如下:

1.定义接口,继承JpaRepository<X,X>,JpaSpecificationExecutor<Project>

public interface ProjectsRepository  extends JpaRepository<Project, Long>, JpaSpecificationExecutor<Project> {
    //...
    @Override
    default List<Project> findAll(Specification<Project> spec) {
        // TODO Auto-generated method stub
        return null;
    }
}

2.service层(UserDetails userDetails这个参数是我根据功能自定义的,可以去掉)

public interface ProjectsService {
    public Page<Project> queryByDynamicSQLPage(Project projectSearch, Integer page, Integer size, UserDetails userDetails);
}

3.Impl实现类,多表关联了用 Join<Organization, Project> join = root.join(“organization”, JoinType.LEFT);

@Service
public class ProjectsServiceImpl implements ProjectsService {
    @Autowired
    ProjectsRepository repository;

      @Override
    public Page<Project> queryByDynamicSQLPage(Project projectSearch,Integer page,Integer size,UserDetails userDetails){//动态查询条件的排序分页
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        return repository.findAll(this.getWhereClause(projectSearch,userDetails),pageable);
    }

   /**查询条件动态组装
     * 动态生成where语句
     * 匿名内部类形式
     * @param projectSearch
     * @return
     */
    private Specification<Project> getWhereClause(final Project projectSearch,UserDetails userDetails){
        return new Specification<Project>() {
            @Override
            public Predicate toPredicate(Root<Project> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();//动态SQL表达式
                List<Expression<Boolean>> exList = predicate.getExpressions();//动态SQL表达式集合
                if( projectSearch.getCheckprojectstatus() != null && !"".equals(projectSearch.getCheckprojectstatus()) ){
                    exList.add(cb.equal(root.get("checkprojectstatus"), projectSearch.getCheckprojectstatus()));
                }
                if( projectSearch.getProjectArea() != null && !"".equals(projectSearch.getProjectArea()) ){
                    exList.add(cb.equal(root.get("projectArea"), projectSearch.getProjectArea()));
                }
                if( projectSearch.getProjectName() != null && !"".equals(projectSearch.getProjectName()) ){
                    exList.add(cb.like(root.<String>get("projectName"), "%" + projectSearch.getProjectName() + "%"));
                }
                if( projectSearch.getPrincipal() != null && !"".equals(projectSearch.getPrincipal()) ){
                    exList.add(cb.like(root.<String>get("principal"), "%" + projectSearch.getPrincipal() + "%"));
                }
                if( projectSearch.getSubjectOriented() != null && !"".equals(projectSearch.getSubjectOriented()) ){
                    exList.add(cb.equal(root.get("subjectOriented"), projectSearch.getSubjectOriented()));
                }
                if( projectSearch.getTeachingSection() != null && !"".equals(projectSearch.getTeachingSection()) ){
                    exList.add(cb.equal(root.get("teachingSection"), projectSearch.getTeachingSection()));
                }
                if( projectSearch.getJobCategory() != null && !"".equals(projectSearch.getJobCategory()) ) {
                    exList.add(cb.equal(root.get("jobCategory"), projectSearch.getJobCategory()));
                }
                    Join<Organization, Project> join = root.join("organization", JoinType.LEFT);
                    exList.add(cb.equal(join.get("login"), userDetails.getUsername()));
                return predicate;
            }
        };
    }
}

4.Controller控制层

@GetMapping("/XXXXXX")
    @Timed
    @PreAuthorize("hasRole(\""+ AuthoritiesConstants.XXXXX +"\")")
    public Map<String, Object> queryProject(@RequestBody Project search, Integer page, Integer rows,@AuthenticationPrincipal UserDetails userDetails) {
        int pageBegin = page - 1;
        Page<Project> list = projectsService.queryByDynamicSQLPage(search, pageBegin, rows,userDetails);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list.getContent());//将所有数据返回list
        map.put("total", list.getTotalElements());//返回元素总数
        return map;
    }

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/115843.html

(0)
Java光头强的头像Java光头强

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!