美文网首页
mybatis-分页查询

mybatis-分页查询

作者: 李霖神谷 | 来源:发表于2019-12-03 23:44 被阅读0次

1.业务需求:
发送第几页,每一页的个数,显示当前页所需要查找的数据。
2.业务逻辑:
在sql中limit可以实现分页,它需要传两个参数一个是从第几行数开始(第一行的行数为零),一个是每一页的个数。xml中能够接收map,根据业务层计算的第几行数和每页个数来实现sql语句的查询。
mapper层:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shuai.mapper.PeopleMapper">
    <select id="findByPage" resultType="com.shuai.pojo.People" parameterType="map">
    select * from people limit  #{currPage},#{pageSize};
    </select>
</mapper>

分页实现层:

package com.shuai.service.impl;

import com.shuai.service.PgeService;

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


public class PgeServiceImpl implements PgeService {
    /**
     * 分页的实现
     *
     * @param currPage 表示第几页
     * @param pageSize 表示一页有几条数据
     * @return
     */
    public Map<String, Object> pageService(Integer currPage, Integer pageSize) {
        Map map = new HashMap();
//       表示从第几个数开始分页
        int currtIndex = pageSize * (currPage - 1);
        map.put("currPage", currtIndex);
        map.put("pageSize",pageSize);
        return map;
    }
}

dao接口层:

public interface PeopleMapper {
   List<People> findByPage(Map<String, Object> map);
}

测试:

import com.shuai.mapper.PeopleMapper;
import com.shuai.pojo.People;
import com.shuai.service.PgeService;
import com.shuai.service.impl.PgeServiceImpl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class test {
    @Test
    public void test1() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Config.xml");
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sf.openSession();
        PgeService pageService=new PgeServiceImpl();
        PeopleMapper peopleMapper= sqlSession.getMapper(PeopleMapper.class);
        List<People> peopleList= peopleMapper.findByPage(pageService.pageService(2,3));
        for (People people : peopleList) {
            System.out.println(people);
        }
    }
}

相关文章

网友评论

      本文标题:mybatis-分页查询

      本文链接:https://www.haomeiwen.com/subject/kgohgctx.html