【spring boot】11.spring-data-jpa的详细介绍和复杂使用

====================================================================================================

项目地址:GitHub地址

复杂jpa查询 会陆续在本项目补充完善!!!!

====================================================================================================

这篇专门用来对spring-data-jpa的详细介绍和复杂使用做一个阐述。

参考文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

这一篇没有系统的使用说明指导文档,只是将项目中涉及到的spring-data-jpa的复杂使用做一个记录和总结使用!!

整片参考项目代码GitHub地址:https://github.com/AngelSXD/myagenorderdiscount

 

过程中参考的文章:

  http://blog.csdn.net/mendeliangyang/article/details/52366799/

  http://blog.csdn.net/lihuapiao/article/details/48782843【关于多表关联查询,这两个链接中有所体现】

====================================================================================================

1.分页

关于分页的使用,无非就是前台传来《1.当前页码》《2.一页几条》,再多一点就是《3.按照什么排序,升序或降序》

所以,很简单的

  1》Repository层

import com.agen.orderdiscount.entity.Discount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * discount 折扣持久化层
 *
 * @author SXD
 * @date 2018/1/8
 */
public interface DiscountRepository extends JpaRepository<Discount,String>{

    @Override
    Page<Discount> findAll(Pageable pageable);
}
View Code

  2》Controller层

@RequestMapping("allDiscount")
    @ResponseBody
    public Page<Discount> allDiscount(){
        Sort sort = new Sort(Sort.Direction.DESC,"editDate");  //sort,根据Discount实体中的editDate字段进行降序
        Pageable pageable = new PageRequest(0,10,sort);      //实例化分页对象,第0页,每页10条,且传入sort
        Page<Discount> page = discountRepository.findAll(pageable); //调用repository层分页查找方法,返回结果
        return  page;
    }

  3》传给前台以后,解析并展示数据

function get10Disocount(){
    $.ajax({url:"admin/allDiscount",
        type:"post",
        traditional:true,
        data:{pageNumber:$("input[name='pageNumber']").val(),pageSize:$("input[name='pageSize']").val()},
        success:function(data){
            if(data != null){
                var temp = "";
                //当前页
                if(data.content.length <10){
                    $("input[name='pageNumber']").val(data.number);
                }else{
                    $("input[name='pageNumber']").val(parseInt(data.number)+1);
                }
                //当前页多少条
                $("input[name='pageSize']").val(data.size);
                //循环分页的content,就是一个List
                $.each(data.content,function(i,d){
                    temp += '<div class="row">'
                        +'<div class="alert alert-info">'
                        +'<div class="row">'
                        +' <div class="col-lg-8 col-sm-12 col-md-12 col-xs-12 text-left">'
                        +' <input type="hidden" name="adminId" value="'+d.adminId+'"/>'
                        +' <u name="adminName">'+d.adminName+'</u>'
                        +' </div>'
                        +' </div>'
                        +'<div class="row">'
                        +' <div class="col-lg-6 col-sm-6 col-md-6 col-xs-6 text-left">'
                        +' <input type="hidden" name="productId" value="'+d.productId+'"/>'
                        +' <small name="productName">'+d.productName+'</small>'
                        +' </div>'
                        +' <div class="col-lg-6  col-sm-6  col-md-6  col-xs-6 text-right">'
                        +' <input type="hidden" name="detailed" value="'+d.discountId+'~'+d.productPrice+'~'+d.priceDiscount+'~'+d.disCre1+'"/>'
                        +' <small>¥<em>'+d.dicountPrice+'</em>&nbsp;折扣价</small>'
                        +' </div>'
                        +'</div>'
                        +'</div>'
                        +'</div>';

                });
                $('.detail .begon').children(":first").before(temp);

            }
        }
    });
}
View Code

 

 

========================================================================================================

2.spring data jpa  复杂查询之  多条件in查询 +分页

想要多条件in查询的话,需要repository接口继承另一个接口JpaSpecificationExecutor

所以

  1》repository层应该如下:

import com.agen.orderdiscount.entity.Discount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

/**
 * discount 折扣持久化层
 *
 * @author SXD
 * @date 2018/1/8
 */
public interface DiscountRepository extends JpaRepository<Discount,String>,JpaSpecificationExecutor<Discount> {

    /**
     * 根据 adminId 和 productId 查找折扣
     * @param adminId
     * @param productId
     * @return
     */
    Discount findDiscountByAdminIdAndProductId(Integer adminId,Integer productId);

    @Override
    Page<Discount> findAll(Pageable pageable);

}
View Code

  2》controller层【我没有写service层,所以直接在controller层拼接的条件】

 @RequestMapping("queryDiscount")
    @ResponseBody
    public Page<Discount> queryDiscount(int pageNumber,int pageSize,String adminIds,String productIds){

        List<Integer> adminArr = getIntArr(adminIds);
        List<Integer> productArr = getIntArr(productIds);
        Pageable pageable = new PageRequest(pageNumber,pageSize);

        Page<Discount> discountList = discountRepository.findAll(new Specification<Discount>() {
            @Override
            public Predicate toPredicate(Root<Discount> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if(!adminArr.isEmpty()){
                    list.add(root.get("adminId").in(adminArr));
                }
                if(!productArr.isEmpty()){
                    list.add(root.get("productId").in(productArr));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("editDate")));

                Predicate[] predicates = new Predicate[list.size()];
                predicates = list.toArray(predicates);
                return criteriaBuilder.and(predicates);
            }
        },pageable);

        return discountList;
    }


    public List<Integer> getIntArr(String str){
        if(Objects.nonNull(str) && str.length()>0){
            List<Integer> adminArr =  Arrays.stream(str.split(",")).map(s->Integer.valueOf(s)).collect(Collectors.toList());
            return  adminArr;
        }else{
            return new ArrayList<>();
        }

    }
View Code

  如果不想分页,返回List<Discount>的话,可以不用传入pageable参数即可!!

  3》页面展示 ajax【相对于上面1.分页,仅仅多传了需要查询的条件字段的值而已】

function get10Disocount(flag){

    var json = new Object();
    json.pageNumber = $("input[name='pageNumber']").val();
    json.pageSize = $("input[name='pageSize']").val();
    if(flag == "query"){
        json.adminIds = $(".checkedAdminIds").val();
        json.productIds = $(".checkedProductIds").val();
    }

    $.ajax({url:"admin/queryDiscount",
        type:"post",
        traditional:true,
        data:json,
        success:function(data){
            if(data != null){
                var temp = "";
                //当前页
                if(data.content.length <10){
                    $("input[name='pageNumber']").val(data.number);
                    if(data.content.length == 0){
                        $(".moreDetail u").text("暂无数据");
                    }else{
                        $(".moreDetail u").text("人家也是有底线的");
                    }
                }else{
                    $("input[name='pageNumber']").val(parseInt(data.number)+1);
                    $(".moreDetail u").text("...加载更多...");
                }
                //当前页多少条
                $("input[name='pageSize']").val(data.size);
                //循环分页的content,就是一个List
                $.each(data.content,function(i,d){
                    temp += '<div class="row">'
                        +'<div class="alert alert-info">'
                        +'<div class="row">'
                        +' <div class="col-lg-8 col-sm-12 col-md-12 col-xs-12 text-left">'
                        +' <input type="hidden" name="adminId" value="'+d.adminId+'"/>'
                        +' <u name="adminName">'+d.adminName+'</u>'
                        +' </div>'
                        +' </div>'
                        +'<div class="row">'
                        +' <div class="col-lg-6 col-sm-6 col-md-6 col-xs-6 text-left">'
                        +' <input type="hidden" name="productId" value="'+d.productId+'"/>'
                        +' <small name="productName">'+d.productName+'</small>'
                        +' </div>'
                        +' <div class="col-lg-6  col-sm-6  col-md-6  col-xs-6 text-right">'
                        +' <input type="hidden" name="detailed" value="'+d.discountId+'~'+d.productPrice+'~'+d.priceDiscount+'~'+d.disCre1+'"/>'
                        +' <small>¥<em>'+d.dicountPrice+'</em>&nbsp;折扣价</small>'
                        +' </div>'
                        +'</div>'
                        +'</div>'
                        +'</div>';

                });

                $('.detail .begon').children(".moreDetail").before(temp);

            }else{
                $(".moreDetail u").text("暂无数据");
            }
        }
    });
}
View Code

 

==============================================================================================================

3.多条件查询

 

posted @ 2017-11-25 11:41  Angel挤一挤  阅读(2668)  评论(0编辑  收藏  举报