环境是idea下的spring全家桶项目,先看代码

 /**
     * @return java.util.List<com.tensquare. .pojo.Label>
     * @Author 
     * @De ion 多条件查询,运用lambda表达式//TODO
     * @Date 2018/12/20 15:28
     * @Param [label]
     **/
    public List<Label> findLabelBySearch(Label label) {
        Specification<Label> specification = (root, query, cb) -> {
            // new一个集合来保存查询的多值
            List<Predicate> list = new ArrayList<>();
            if (StringUtil.isNotEmpty(label.getLabelname())) {
                // labelname like \"%小明%\"
                Predicate predicate = cb.like(root.get(\"labelname\").as(String.class), \"%\" + label.getLabelname() + \"%\");
                list.add(predicate);
            }
            if (StringUtil.isNotEmpty(label.getState())) {
                // state = \"1\"
                Predicate predicate = cb.equal(root.get(\"state\").as(String.class), label.getState());
                list.add(predicate);
            }
            // 保存最终返回值的条件
            Predicate[] predicates = new Predicate[list.size()];
            // 集合转成数组
            list.toArray(predicates);
            return cb.and(predicates);
        };
        // 解析成sql语句进行多条件查询
        // where labelname like \"%小明%\" and state = \"1\"
        return labelDao.findAll(specification);
    }

最近在研究springdata,其中,jpa中的Specification在jdk8的环境中是不能直接new,例如这样

return labelDao.findAll( new Specification<Label>(){

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery,         
                   CriteriaBuilder criteriaBuilder) {
                return null;
            }
        });
会出错,错误如下
Anonymous new Specification<Label>() can be replaced with lambda less... (Ctrl+F1) 
Inspection info: This inspection reports all anonymous classes which can be replaced with lambda  s
Lambda syntax is not supported under Java 1.7 or earlier JVMs.

大概的意思是jdk8环境下不能直接new,必须使用lambda表达式,然后就直接改成lambda表达式就行了 ,如果大家看到后又不一样的建议欢迎留言!

收藏 打印