一聚教程网:一个值得你收藏的教程网站

热门教程

Spring MVC结合Spring Data JPA实现按条件查询和分页

时间:2022-06-29 01:06:25 编辑:袖梨 来源:一聚教程网

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有。

后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 (实现方法主要在SbglServiceImpl.java类中)

前台表现:用kkpaper表现出来

实现效果:

1、实体类

package com.jinhetech.yogurt.sbgl.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.springframework.cache.annotation.Cacheable;
@Entity
@Table(name="SYS_SBGL")
@PrimaryKeyJoinColumn(name = "SBBM")
@Cacheable(value = "baseCache")
public class Sbgl implements Serializable{


  private static final long serialVersionUID = -1423899016746755470L;

  @Id
  private String sbbm;
  
  private String sbmc;
  private String sblx;
  private String sssx;
  private String ssjd;
  
  private String azsj;
  private String azry;
  private String sbzt;
  private String sbjd;
  private String sbwd;
  
  private String wxlxr;
  private String wxlxdh;
  private String sbywxcs;
  private String jzpylyz;
  private String mqsbcyr;
  private String bzsm;
  
    
  //setter、getter方法省略
  
}

2、jsp页面,看最下面的分页组件(kkpaper)

resultMap集合是下面Controller中最后查询和分页后获得的所有数据信息,resultMap.resultList:resultList是Map集合的属性,里面存着数据

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>






  设备管理
  
  css/zTreeStyle.css" rel="external nofollow" type="text/css">
  
  
  
  
  
  
  
  
  
  
  



  
首页 > 设备管理 > 设备列表
设备名称:
  设备类型:
  所属市县:
  基地名称:
  设备状态:
    
共查询出数据结果:${resultMap.totalNum}
设备名称 设备类型 所属市县 基地名称 设备状态 维修联系人 联系电话 设备持有人 操作
${sbgl.sbmc } ${sbgl.sblx } ${sbgl.sssx } ${sbgl.ssjd } ${sbgl.sbzt } ${sbgl.wxlxr } ${sbgl.wxlxdh } ${sbgl.mqsbcyr } 修改 | 查看

3、Controller(看红色字体下面那个处理方法)

package com.jinhetech.yogurt.sbgl.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import com.jinhetech.yogurt.dictionary.crop.service.impl.CropServiceImpl;
import com.jinhetech.yogurt.func.entity.Func;
import com.jinhetech.yogurt.func.service.FuncService;
import com.jinhetech.yogurt.menu.entity.Menu;
import com.jinhetech.yogurt.menu.service.MenuService;
import com.jinhetech.yogurt.menu.util.MenuUtil;
import com.jinhetech.yogurt.organization.entity.OrgTable;
import com.jinhetech.yogurt.organization.service.OrgService;
import com.jinhetech.yogurt.organization.util.OrgUtil;
import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.role.service.RoleService;
import com.jinhetech.yogurt.sbgl.dao.SbglDao;
import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.sbgl.service.SbglService;
import com.jinhetech.yogurt.sbgl.util.SbglUtil;
import com.jinhetech.yogurt.user.entity.User;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.user.service.UserService;
import com.jinhetech.yogurt.user.util.UserUtil;
import com.jinhetech.yogurt.util.base.BaseController;
import com.jinhetech.yogurt.util.base.Constants;
import com.jinhetech.yogurt.util.common.TextUtils;
import com.jinhetech.yogurt.util.common.UUIDHexGenerator;

/**
 * 系统用户管理控制类
 * 
 * @author Wang Hao
 * @version 1.0 2014-02-28 初版
 */
@Controller("sbglController")
@RequestMapping("/sbgl")
public class SbglController extends BaseController {
//  @Resource(name = "sbglDao")
//  private SbglDao sbglDao;
  
  @Resource(name = "sbglService")
  private SbglService sbglService;
  
  /**
   * 平台权限管理导航*/
  @RequestMapping("/home_list")
  public ModelAndView home() {

    return new ModelAndView("iot/permis/permis_home");
  }
  
  
  /**
   * 查询设备信息列表(支持分页和多条件查询)。
   * 
   */
  @RequestMapping("sbgl_list")
  @RequiresRoles("sbgl/sbgl_list")
  public String getUserList(Model model) throws Exception {
    //显示设备列表
//    List lst=new ArrayList();
//    lst=(List) sbglService.getAll();
    
    Map resultMap = null;
    // 查询表单或分页保持请求时 请求参数的接收
    Map serArgs = new HashMap();
    serArgs = SbglUtil.getSelArgsToMap(request);//这个类在下面给出
    

    resultMap = sbglService.getUserBySearch(serArgs, "wxlxdh");
    
    model.addAttribute("resultMap", resultMap);
//    model.addAttribute("lst", lst);

    return "sbgl/sbgl_list";
  }

  /**
   * 新增设备信息列表(支持分页和多条件查询)。
   * 
   * @author YangZhenghua 2014-5-28
   * @throws Exception
   */
  @RequestMapping("sbgl_add_list")
  @RequiresRoles("sbgl/sbgl_add_list")
  public String getAddList(Model model) throws Exception {

    
    System.out.println("aaa");
    model.addAttribute("aaa","aaa");
    model.addAttribute("resultMap", "hello world");
    

    return "sbgl/sbgl_add_list";
  }
  
  
  /**
   * 保存、修改用户信息。
   * 
   * @author YangZhenghua 2014-5-28
   * @throws Exception
   */
  @RequestMapping("sbgl_save_list")
  @RequiresRoles("sbgl/sbgl_save_list")
  public ModelAndView SaveSbgl(Sbgl sbgl) throws Exception {

    String sbmc=request.getParameter("sbmc");
    String sblx=request.getParameter("sblx");
    String sssx=request.getParameter("sssx");
    String ssjd=request.getParameter("ssjd");
    String azsj=request.getParameter("azsj");
    
    String azry=request.getParameter("azry");
    String sbzt=request.getParameter("sbzt");
    String sbjd=request.getParameter("sbjd");
    String sbwd=request.getParameter("sbwd");
    String wxlxr=request.getParameter("wxlxr");
    
    String wxlxdh=request.getParameter("wxlxdh");
    String sbywxcs=request.getParameter("sbywxcs");
    String jzpylyz=request.getParameter("jzpylyz");
    String mqsbcyr=request.getParameter("mqsbcyr");
    String bzsm=request.getParameter("bzsm");
    
    sbgl.setSbbm(UUIDHexGenerator.generate());
    sbgl.setSbmc(sbmc);
    sbgl.setSblx(sblx);
    sbgl.setSssx(sssx);
    sbgl.setSsjd(ssjd);
    sbgl.setAzsj(azsj);
    
    sbgl.setAzry(azry);
    sbgl.setSbzt(sbzt);
    sbgl.setSbjd(sbjd);
    sbgl.setSbwd(sbwd);
    sbgl.setWxlxr(wxlxr);
    
    sbgl.setWxlxdh(wxlxdh);
    sbgl.setSbywxcs(sbywxcs);
    sbgl.setJzpylyz(jzpylyz);
    sbgl.setMqsbcyr(mqsbcyr);
    sbgl.setBzsm(bzsm);

    sbglService.save(sbgl);

    return new ModelAndView(new RedirectView("sbgl_list"));
  }


}

3.2、SbglUtil.java

封装从前台传递过来的查询参数、前台传递过来的分页参数,都放到Map集合serArgs中

package com.jinhetech.yogurt.sbgl.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jinhetech.yogurt.organization.entity.OrgTable;
import com.jinhetech.yogurt.report.entity.Report;
import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.user.entity.User;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.util.common.JSONUtils;
import com.jinhetech.yogurt.util.common.TextUtils;

/**
 * 用户功能模块工具类。
 * 
 * @author YangZhenghua
 * @version V1.0 2014-5-16 初版
 * 
 */
public class SbglUtil {

  /**
   * 封装从前台传递过来的查询参数。
   * 
   * @author YangZhenghua
   * @date 2014-6-26
   */
  public static Map getSelArgsToMap(HttpServletRequest request) throws Exception {
    Map serArgs = new HashMap();

    String serSbmc = request.getParameter("serSbmc");
    String serSblx = request.getParameter("serSblx");
    String serSssx = request.getParameter("serSssx");
    String serJdmc = request.getParameter("serJdmc");
    String serSbzt = request.getParameter("serSbzt");
    
    String pageNum = request.getParameter("pageNum") == null ? "1" : request.getParameter("pageNum");
    String pageSize = request.getParameter("pageSize") == null ? "10" : request.getParameter("pageSize");


    //serArgs.put("serUserName", java.net.URLDecoder.decode(serUserName == null ? "" : serUserName, "UTF-8"));
    serArgs.put("serSbmc", serSbmc);
    serArgs.put("serSblx", serSblx);
    serArgs.put("serSssx", serSssx);
    serArgs.put("serJdmc", serJdmc);
    serArgs.put("serSbzt", serSbzt);
    
    serArgs.put("pageNum", pageNum);
    serArgs.put("pageSize", pageSize);

    return serArgs;
  }



}

3.3、SbglService.java

package com.jinhetech.yogurt.sbgl.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinhetech.yogurt.sbgl.entity.Sbgl;


public interface SbglService {

  public List getAll() throws Exception;
  
  public Sbgl save(Sbgl sbgl) throws Exception;
  
  public Map getUserBySearch(Map serArgs, final String sortType) throws Exception;
  
}

3.4、SbglServiceImpl.java (根据前台传递来的查询参数进行查询,获得的结果数据放到Page objPage参数)

package com.jinhetech.yogurt.sbgl.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.ListJoin;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jinhetech.yogurt.role.entity.Role;
import com.jinhetech.yogurt.sbgl.dao.SbglDao;
import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.sbgl.service.SbglService;
import com.jinhetech.yogurt.user.entity.UserInfo;
import com.jinhetech.yogurt.util.common.PageUtils;
import com.jinhetech.yogurt.util.common.TextUtils;

@Service("sbglService")
@Transactional
public class SbglServiceImpl implements SbglService{

  @Resource(name = "sbglDao")
  private SbglDao sbglDao;
  
  
  public List getAll() throws Exception{
    
    return (List) this.sbglDao.findAll();
  }

  public Sbgl save(Sbgl sbgl) throws Exception {
    return sbglDao.save(sbgl);
  }
  
  
  /**
   * 查询用户信息列表(支持分页和多条件查询)。
   * 
   * @author YangZhenghua 2014-6-19
   */
  public Map getUserBySearch(final Map serArgs, final String sortType) throws Exception {

    // 获得分页对象pageable,并且在pageable中页码是从0开始,设定按照sortType升序排列
    Pageable pageable = PageUtils.buildPageRequest(Integer.valueOf(serArgs.get("pageNum")),
        Integer.valueOf(serArgs.get("pageSize")), sortType);

    Page objPage = sbglDao.findAll(new Specification() {

      public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        List lstPredicates = new ArrayList();

        if (TextUtils.isNotBlank(serArgs.get("serSbmc"))) {
          lstPredicates.add(cb.like(root.get("sbmc").as(String.class), "%" + serArgs.get("serSbmc") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serSblx"))) {
          lstPredicates.add(cb.like(root.get("sblx").as(String.class), "%" + serArgs.get("serSblx") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serSssx"))) {
          lstPredicates.add(cb.like(root.get("sssx").as(String.class), "%" + serArgs.get("serSssx") + "%"));
        }
        if (TextUtils.isNotBlank(serArgs.get("serJdmc"))) {
          lstPredicates.add(cb.like(root.get("jdmc").as(String.class), "%" + serArgs.get("serJdmc") + "%"));
        }

        if (TextUtils.isNotBlank(serArgs.get("serSbzt"))) {
          lstPredicates.add(cb.equal(root.get("sbzt"), serArgs.get("serSbzt")));
        }

        Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
        return cb.and(lstPredicates.toArray(arrayPredicates));
      }
    }, pageable);

    return PageUtils.getPageMap(objPage);
  }
  
  
}

3.4.1、PageUtils.java(分页数据工具类)

package com.jinhetech.yogurt.util.common;

import java.util.HashMap;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.jinhetech.yogurt.util.base.Constants;

/**
 * 分页数据工具类。
 * 
 * @author YangZhenghua
 * @version V1.0 2014-6-24 初版
 * 
 */
public class PageUtils {

  /**
   * 封装分页数据到Map中。
   */
  public static Map getPageMap(Page objPage) {
    Map resultMap = new HashMap();

    resultMap.put(Constants.PAGE_RESULT_LIST, objPage.getContent()); // 数据集合
    resultMap.put(Constants.PAGE_TOTAL_NUM, objPage.getTotalElements()); // 总记录数
    resultMap.put(Constants.PAGE_TOTAL_PAGE, objPage.getTotalPages()); // 总页数
    resultMap.put(Constants.PAGE_NUM, objPage.getNumber()); // 当前页码
    resultMap.put(Constants.PAGE_SIZE, objPage.getSize()); // 每页显示数量

    return resultMap;
  }

  /**
   * 创建分页请求。
   * 
   * @author YangZhenghua
   * @date 2014-7-14
   * 
   * @param pageNum 当前页
   * @param pageSize 每页条数
   * @param sortType 排序字段
   * @param direction 排序方向
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType, String direction) {
    Sort sort = null;

    if (!TextUtils.isNotBlank(sortType)) {
      return new PageRequest(pageNum - 1, pageSize);
    } else if (TextUtils.isNotBlank(direction)) {
      if (Direction.ASC.equals(direction)) {
        sort = new Sort(Direction.ASC, sortType);
      } else {
        sort = new Sort(Direction.DESC, sortType);
      }
      return new PageRequest(pageNum - 1, pageSize, sort);
    } else {
      sort = new Sort(Direction.ASC, sortType);
      return new PageRequest(pageNum - 1, pageSize, sort);
    }
  }

  /**
   * 创建分页请求(该方法可以放到util类中).
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, String sortType) {
    return buildPageRequest(pageNum, pageSize, sortType, null);
  }
  
  /**
   * 创建分页请求
   * 
   * @author YangZhenghua
   * @date 2014-11-12
   * 
   * @param pageNum
   * @param pageSize
   * @param sort
   * @return
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize, Sort sort) {
    return new PageRequest(pageNum - 1, pageSize, sort);
  }

  /**
   * 创建分页请求(该方法可以放到util类中).
   */
  public static PageRequest buildPageRequest(int pageNum, int pageSize) {
    return buildPageRequest(pageNum, pageSize, null, null);
  }

}

 4、DAO(SbglDao.java),对,只需要继承Spring Data JPA的PagingAndSortingRepository接口,Controller中调用其findAll()方法

package com.jinhetech.yogurt.sbgl.dao;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import com.jinhetech.yogurt.sbgl.entity.Sbgl;
import com.jinhetech.yogurt.user.entity.UserInfo;

@Repository("sbglDao")
public interface SbglDao extends PagingAndSortingRepository, JpaSpecificationExecutor {
  
  
}

热门栏目