JdbcTemplate+PageImpl实现多表分页查询

一、基础实体 

@MappedSuperclass
public abstract class AbsIdEntity implements Serializable {

    private static final long serialVersionUID = 7988377299341530426L;

    public final static int IS_DELETE_YES = 1;// 标记删除
    public final static int IS_DELETE_NO = 0;// 未删除,保留的

    @Id
    @GenericGenerator(name="uuid", strategy="uuid")
    @GeneratedValue(generator="uuid")
    protected String id;

    @Column(name = "creationtime")
    protected Timestamp creationTimestamp = new Timestamp(System.currentTimeMillis());

    @Column(name = "lastmodifiedtime")
    protected Timestamp modificationTimestamp;

    @Column(name = "dr")
    protected int dr;// 是否删除。0:未删除;1:已删除

    /**
     * 主键,对应id字段
     */
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }

    /**
     * 创建日期,对应ts_insert字段
     */
    public Timestamp getCreationTimestamp() { return creationTimestamp; }
    public void setCreationTimestamp(Timestamp creationTimestamp) { this.creationTimestamp = creationTimestamp; }

    /**
     * 修改日期,对应ts_update字段
     */
    public Timestamp getModificationTimestamp() { return modificationTimestamp; }
    public void setModificationTimestamp(Timestamp modificationTimestamp) { this.modificationTimestamp = modificationTimestamp; }

    /**
     * 是否删除,对应dr字段
     * @return
     */
    public int getDr() {
        return dr;
    }
    public void setDr(int dr) {
        this.dr = dr;
    }

}

二、扩展VO

import java.io.Serializable;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import xxx.entity.AbsIdEntity;

public class StaffUnionVO extends AbsIdEntity implements Serializable, RowMapper<StaffUnionVO>{
    /**
     *
     */
    private static final long serialVersionUID = -5213225066818183479L;

    private String code;// 员工编码

    private String name;// 员工姓名

    private int sex; // 性别

    private Date birthday;// 出生年月日

    private String deptId;// 人员所属部门

    private String companyId;//人员所属公司表

    private EnumStatus status;// 员工状态,在职,离职

    private String nativePlace;// 籍贯

    private String education;// 学历

    private EnumPoliticalStatus politicalStatus;// 政治面貌

    private String major;// 所学专业

    private String school;// 毕业学校

    private Date graduationTime;// 毕业时间

    private Date workTime;// 参加工作时间

    private String credentialCode;// 证件号码

    private String mobile;// 移动电话

    private String signPic;// 签名图片

    private String landlineNum;// 座机号

    private String age;// 年龄

    private String post;// 职位  

    private String positionId;// 岗位Id

    private String dept;// 部门

    private String email;// 邮箱

    private String  userId;// 用户关联人员

    private int  isUser;// 是否关联人员

    private int credentialType;//证件类型

    private String address;//地址

    private String staffTypeId;//人员id

    private String property;//直属或隶属

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getPositionId() {
        return positionId;
    }

    public void setPositionId(String positionId) {
        this.positionId = positionId;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getStaffTypeId() {
        return staffTypeId;
    }

    public void setStaffTypeId(String staffTypeId) {
        this.staffTypeId = staffTypeId;
    }

    public int getCredentialType() {
        return credentialType;
    }

    public void setCredentialType(int credentialType) {
        this.credentialType = credentialType;
    }

    public int getIsUser() {
        return isUser;
    }

    public void setIsUser(int isUser) {
        this.isUser = isUser;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getLandlineNum() {
        return landlineNum;
    }

    public void setLandlineNum(String landlineNum) {
        this.landlineNum = landlineNum;
    }

    public String getDeptId() {
        return deptId;
    }

    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }

    public String getPosition() {
        return positionId;
    }

    public void setPosition(String position) {
        this.positionId = position;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public EnumStatus getStatus() {
        return status;
    }

    public void setStatus(EnumStatus status) {
        this.status = status;
    }

    public String getNativePlace() {
        return nativePlace;
    }

    public void setNativePlace(String nativePlace) {
        this.nativePlace = nativePlace;
    }

    public String getEducation() {
        return education;
    }

    public void setEducation(String education) {
        this.education = education;
    }

    public EnumPoliticalStatus getPoliticalStatus() {
        return politicalStatus;
    }

    public void setPoliticalStatus(EnumPoliticalStatus politicalStatus) {
        this.politicalStatus = politicalStatus;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public Date getGraduationTime() {
        return graduationTime;
    }

    public void setGraduationTime(Date graduationTime) {
        this.graduationTime = graduationTime;
    }

    public Date getWorkTime() {
        return workTime;
    }

    public void setWorkTime(Date workTime) {
        this.workTime = workTime;
    }

    public String getCredentialCode() {
        return credentialCode;
    }

    public void setCredentialCode(String credentialCode) {
        this.credentialCode = credentialCode;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getSignPic() {
        return signPic;
    }

    public void setSignPic(String signPic) {
        this.signPic = signPic;
    }

    @Override
    public StaffUnionVO mapRow(ResultSet rs, int row) throws SQLException {
        StaffUnionVO vo = new StaffUnionVO();
        vo.setAddress(rs.getString("address"));
        vo.setAge(rs.getString("age"));
        vo.setBirthday(rs.getDate("birthday"));
        vo.setCode(rs.getString("code"));
        vo.setCompanyId(rs.getString("companyId"));
        vo.setCreationTimestamp(rs.getTimestamp("creationtime"));
        vo.setCredentialCode(rs.getString("credentialCode"));
        vo.setCredentialType(rs.getInt("credentialType"));
        vo.setDept(rs.getString("dept"));
        vo.setDeptId(rs.getString("deptId"));
        vo.setDr(rs.getInt("dr"));
        vo.setEducation(rs.getString("education"));
        vo.setEmail(rs.getString("email"));
        vo.setGraduationTime(rs.getDate("graduationTime"));
        vo.setId(rs.getString("id"));
        vo.setIsUser(rs.getInt("isUser"));
        vo.setLandlineNum(rs.getString("landlineNum"));
        vo.setMajor(rs.getString("major"));
        vo.setMobile(rs.getString("mobile"));
        vo.setModificationTimestamp(rs.getTimestamp("lastmodifiedtime"));
        vo.setName(rs.getString("name"));
        vo.setNativePlace(rs.getString("nativePlace"));
        vo.setPoliticalStatus(rs.getString("politicalStatus") == null || "".equals(rs.getString("politicalStatus").trim()) ? null : EnumPoliticalStatus.valueOf(rs.getString("politicalStatus")));
        vo.setPositionId(rs.getString("positionId"));
        vo.setPost(rs.getString("post"));
        vo.setProperty(rs.getString("property"));
        vo.setSchool(rs.getString("school"));
        vo.setSex(rs.getInt("sex"));
        vo.setSignPic(rs.getString("signPic"));
        vo.setStaffTypeId(rs.getString("staffTypeId"));
        vo.setStatus(rs.getString("status") == null || "".equals(rs.getString("status").trim()) ? null : EnumStatus.valueOf(rs.getString("status")));
        vo.setUserId(rs.getString("userId"));
        vo.setWorkTime(rs.getDate("workTime"));

        return vo;
    }
}

三、使用JdbcTemplate 进行联表查询操作

@Repository
public class StaffUnionDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<StaffUnionVO> getStaffUnion(String deptId, String param) {     //sql中联表查询,自定义列名
        String sql = "select bs.id id, bs.creationtime creationtime, bs.lastmodifiedtime lastmodifiedtime, bs.dr dr, bs.code code, bs.name name, bs.sex sex, bs.birthday birthday, bsp.dept_id as deptId, bsp.company_id companyId,"
                   + "bs.status status, bs.native_place nativePlace, bs.education education, bs.political_status politicalStatus, bs.major major, bs.school school, bs.graduation_time graduationTime, bs.work_time workTime,"
                   + "bs.credential_code credentialCode, bs.mobilephone_num mobile, bs.sign_pic signPic, bs.landline_num landlineNum, bs.age age, bs.post post, bsp.position positionId, bs.dept dept, bs.is_user isUser,"
                   + "bs.email email, bs.userid userId, bs.credential_type credentialType, bs.address address, bs.staff_type_id staffTypeId, bsp.property property from bd_staff bs, bd_staff_partjob bsp where bs.id = bsp.staff_id and bsp.dr = 0";

        //String sqlx = "select bs.id id from bd_staff bs, bd_staff_partjob bsp where bs.id = bsp.staff_id and bsp.dr = 0";

        if(deptId != null) {
            sql += "and bsp.dept_id = " + deptId;
        }
        if(param != null) {
            sql += " and (bs.code like %" + param + "% or bs.name like %" + param + "%)";
        }     (1)
    //该方法无法实现类中变量是对象时的转换,例如存在枚举对象。
        //List<StaffUnionVO> result = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(StaffUnionVO.class));
        (2)
//        可以自定义转化
//        @SuppressWarnings("unchecked")
//        List<StaffUnionVO> result = jdbcTemplate.query(sqlx,  new RowMapper() {
//              @Override
//              public Object mapRow(ResultSet rs, int n)  throws SQLException {
//                  StaffUnionVO vo = new StaffUnionVO();
//                  vo.setId(rs.getString("id"));
//                  return vo;
//              }
//        });
       (3)
    //自定义映射方式的实现写在了 StaffUnionVO类中
        List<StaffUnionVO> result = jdbcTemplate.query(sql, new StaffUnionVO());

        return result;
    }
}

四、使用PageImpl进行分页

  @Autowired
    private StaffUnionDao newPageDao;

    @RequestMapping(path = "newpage", method = RequestMethod.GET)
    @ResponseBody
    public PageImpl<StaffUnionVO> getStaffInfoNew(@RequestParam(value = "deptId", required = false) String deptId,
            @RequestParam(value = "searchText", required = false) String param,
            @RequestParam("pageNumber") int pageNumber, @RequestParam("pageSize") int pageSize) {
        List<StaffUnionVO> content = newPageDao.getStaffUnion(deptId, param);
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
        PageImpl<StaffUnionVO> ans = new PageImpl<StaffUnionVO>(content, pageRequest, content == null ? 0 : content.size());
        return ans;
    }

五、补充一种场景

  进行分页查询的时候一般多是针对一个实体(对应一个表),通常使用的spring data jpa 的接口 JpaSpecificationExecutor<T>, 接口内容如下。

JpaSpecificationExecutor

public interface JpaSpecificationExecutor<T> {

    /**
     * Returns a single entity matching the given {@link Specification}.
     *
     * @param spec
     * @return
     */
    T findOne(Specification<T> spec);

    /**
     * Returns all entities matching the given {@link Specification}.
     *
     * @param spec
     * @return
     */
    List<T> findAll(Specification<T> spec);

    /**
     * Returns a {@link Page} of entities matching the given {@link Specification}.
     *
     * @param spec
     * @param pageable
     * @return
     */
    Page<T> findAll(Specification<T> spec, Pageable pageable);

    /**
     * Returns all entities matching the given {@link Specification} and {@link Sort}.
     *
     * @param spec
     * @param sort
     * @return
     */
    List<T> findAll(Specification<T> spec, Sort sort);

    /**
     * Returns the number of instances that the given {@link Specification} will return.
     *
     * @param spec the {@link Specification} to count instances for
     * @return the number of instances
     */
    long count(Specification<T> spec);
}

  分页查询的结果是实体类的集合,通常在服务层完成。但是我们一般不让业务层直接接触我们的实体类,所以就是产生了VO类,也就是服务层不再返回实体类的集合,而是返回VO类的集合,业务层操作的其实是VO类。这样就显得层次清晰,方便控制。例如分页查询,具体实现如下。

  请参考: 后台json格式设计 PagableResponse(分页json格式)  ,生成查询Specification  QueryTool工具

Controller

  @Autowired
    private RoleService roleService;

    @RequestMapping(path = "page")
    @ResponseBody
    public PagableResponse<RoleVO> getPageableRole(@RequestParam(value = "roleId", required = false) String roleId,
            @RequestParam(value = "searchText", required = false) String param,
            @RequestParam("pageNumber") int pageNumber, @RequestParam("pageSize") int pageSize) {
        PagableResponse<RoleVO> response = new PagableResponse<RoleVO>();
        response.setPageNumber(pageNumber);
        response.setPageSize(pageSize);
        PageRequest pageRequest = new PageRequest(pageNumber, pageSize);
        try {
            List<RoleVO> data = roleService.findPageableRoles(param, roleId, pageRequest);
            long count = roleService.count(param, roleId);
            response.setList(data);
            response.setCount(count);
            response.setCode(ReturnCode.SUCCESS);
            response.setMsg("获取角色信息成功!");
        } catch(Exception e) {
            e.printStackTrace();
            response.setCode(ReturnCode.FAILURE);
            response.setMsg("获取角色信息失败!");
        }
        return response;
    }

Service

  @Override
    public List<RoleVO> findPageableRoles(String param, String relyCondition, PageRequest pageRequest) {
        List<RoleVO> list = new ArrayList<RoleVO>();
        Map<String, Object> map = QueryTool.parseCondition(relyCondition);
        //添加搜索添加
        if(StringUtils.isNotBlank(param)){
            map.put(Operator.LIKE+"_roleName", param);
            map.put(Operator.LIKE+"_roleCode", relyCondition);
            map.put(Operator.LIKE+"_roleType", relyCondition);
            map.put(Operator.LIKE+"_roleProperty", relyCondition);
        }
        if(StringUtils.isNotBlank(relyCondition)) {
            map.put(Operator.LIKE+"_id", relyCondition);
        }
        map.put(Operator.EQ+"_dr", "0");
        Specification<RoleEntity> spec = QueryTool.buildSpecification(map, RoleEntity.class);
        Page<RoleEntity> page = roleDao.findAll(spec, pageRequest);
        for (RoleEntity entity : page) {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(entity, roleVO);
            list.add(roleVO);
        }
        return list;
    }

六、其他通过Specification实现分页查询,请参考

springmvc+jpa实现分页的两种方式

时间: 2024-10-12 04:25:04

JdbcTemplate+PageImpl实现多表分页查询的相关文章

SQLServer多表联查,多表分页查询

多表联查: select p.*,s.Sheng , i.Shifrom  [dbo].[ProductRecordInfo]   --表名 p left join [ShengInfo] s on p.ShengInfo = s.ShengId   --使用left join左连接 让两个表中的指定字段产生连接关系left join [ShiInfo] i on p.ShiInfo = i.ShiId          --使用left join左连接 让三个表中的指定字段产生连接关系 这里的

RDIFramework.NET 中多表关联查询分页实例

RDIFramework.NET 中多表关联查询分页实例 RDIFramework.NET,基于.NET的快速信息化系统开发.整合框架,给用户和开发者最佳的.Net框架部署方案.该框架以SOA范式作为指导思想,作为异质系统整合与互操作性.分布式应用提供了可行的解决方案. 分页非常的常见,基本任何项目都会涉及到分页,这没什么好谈的,大多数我们分页对单表的分页比较多,对多表的分页我们可以通过视图来实现,当然还有其他的方式,在这儿,我以一个实例展示下使用我们的RDIFramework.NET来实现多表

Java链接HBASE数据库,创建一个表,删除一张表,修改表,输出插入,修改,数据删除,数据获取,显示表信息,过滤查询,分页查询,地理hash

准备工作 1.创建Java的Maven项目 创建好的目录结构如下:  另外注意junit的版本,最好不要太高,最开始笔者使用的junit4.12的,发现运行的时候会报错.最后把Junit的版本改成4.7的之后,问题解决了. 创建测试工具类HbaseDemo,为了保证能够让Hbase运行,需要最开始写出如下配置: package toto.com.hbase; import java.util.ArrayList; import java.util.Iterator; import org.apa

数据库SQL Server2012笔记(四)——多表查询、子查询、分页查询、用查询结果创建新表和外连接

1.多表查询 1)笛卡尔集: select  *  from  表名1,表名2 select  *  from  表名1,表名2  where   表名1.字段名=表名2.字段名 注: 若有两张表有相同名字的字段,则使用时需带表名(别名). order  by  置于where 条件之后. 2)自连接:同一张表的连接查询,将一张表视为两张表或多张表. eg:显示公司每个员工名字和他的上级的名字.将emp表看做两张表worker和boss select  worker.ename  雇员,boss

.net通用CMS快速开发框架——问题:Dapper通用的多表联合分页查询怎么破?

最近在弄一个东东,类似那种CMS的后台管理系统,方便作为其它项目的初始化框架用的. 现在遇到个问题,如标题所示:Dapper通用的多表联合分页查询怎么破? 单表的话很简单就可以实现,多表不通用的话也可以很方便的实现,那么如果多表通用的话,怎么办呢? 难道只能通过拼接sql或者使用存储过程吗?我先来展示下我的实现方式,希望你有更好的方式,然后同我分享一下,以便解决我的困扰. 技术选型:MVC5.Mysql.Dapper.Autofac.Layui.阿里巴巴矢量库.T4(后面补上). 我选择的都是轻

序列化表单为json对象,datagrid带额外参提交一次查询 后台用Spring data JPA 实现带条件的分页查询

查询窗口中可以设置很多查询条件 表单中输入的内容转为datagrid的load方法所需的查询条件向原请求地址再次提出新的查询,将结果显示在datagrid中 转换方法看代码注释 <td colspan="2"><a id="searchBtn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'"&g

表单查询和分页查询和查询排序

分页查询: 用score表示范: 写法和结构: 解析:limit后面显示的是 起始行(从0开始,第一条就代表0)和每行显示的条数 分页:limit(当前页-1)*每页的显示条数,每页显示的条数. 例如:第一页就是(1-1)x2,2  第二页就是(2-1)x2,2 第三页就是(3-1)x2,2 以此类推 查询排序(order by ): 升序/正序:是从小到大  ase 降序/倒序:是从大到小  desc order by desc: order by ase: 解析:排序要放到最后看,先看结果

thinkphp两表,多表联合查询及分页的连贯操作写法

ThinkPHP中关联查询(即多表联合查询)可以使用 table() 方法或和join方法,具体使用如下例所示: 1.原生查询示例: 代码如下: $Model = new Model(); $sql = 'select a.id,a.title,b.content from think_test1 as a, think_test2 as b where a.id=b.id '.$map.' order by a.id '.$sort.' limit '.$p->firstRow.','.$p-

bos 第4 (区域excel批量导入、区域通用分页查询、分区的添加、分区多条件分页查询、分区导出excel)

BOS项目笔记 第4天 今天内容安排: 1.区域批量导入功能 jQuery OCUpload(一键上传插件).apache POI.pinyin4j 2.实现区域的分页查询 3.对分页代码重构 4.添加分区(combobox下拉框) 5.分区的组合条件分页查询 6.分区数据导出功能 1. 区域数据批量导入功能 1.1 一键上传插件使用 ajax不能做文件上传. 第一步:在jsp页面中引入插件的js文件 <script type="text/javascript" src=&quo