JPA实现动态查询

2024-06-19 15:21:48 浏览数 (1)

JPA实现动态查询

前言

之前使用jpa的时候一直感慨它的一些原来就有的方法很好用,一边不是很习惯这种不是xml写sql的方式,尤其在用习惯了mybatis之后,在使用jpa写动态查询的时候真的一头雾水,直到发现了Specification 这个神奇的东西,使用下来觉得他和mybatis plus的条件构造器很像,而且可以实现动态查询,特意记录一下

代码

JPA

代码语言:javascript复制
 List<Apply> findAll(Specification<Apply> specification);

service

代码语言:javascript复制
 public List<Apply> getAllDynamatic(Apply apply) {
        Specification<Apply> queryCondition = new Specification<Apply>() {
            @Override
            public Predicate toPredicate(Root<Apply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                // 根据传递的对象来进行条件的构造
                if (apply.getId() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("id"), apply.getId()));
                }
                if (apply.getState() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("state"), apply.getState()));
                }
                if (apply.getAwardtype() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("awardtype"), apply.getAwardtype()));
                }
                if (apply.getStudentid() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("studentid"), apply.getStudentid()));
                }
                if (apply.getInfo() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("info"), apply.getInfo()));
                }
                if (apply.getName() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("name"), apply.getName()));
                }
                if (apply.getType() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("type"), apply.getType()));
                }
                if (apply.getTeacherid() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("teacherid"), apply.getTeacherid()));
                }
                if (apply.getTeacherstate() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("teacherstate"), apply.getTeacherstate()));
                }
                if (apply.getProcess() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("process"), apply.getProcess()));
                }
                if (apply.getProcess2() != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("process2"), apply.getProcess2()));
                }

                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return applyRepos.findAll(queryCondition);
    }

这样就实现了jpa的动态查询

0 人点赞