Mybatis 分页(limit)

2,751 阅读1分钟

直接在Mapper.xml中写sql

  • Mapper.java
public interface PeopleMapper {
    List<People> limit(Map<String, Object> map);
}
  • Mapper.xml
<?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.mybatis.DAO.PeopleMapper">
    <resultMap id="PMap" type="P">
        <result column="id" property="idid"/>
    </resultMap>
    <select id="limit" parameterType="map" resultType="P">
        select * from mybatis.people limit #{startindex},#{pagesize};
    </select>
</mapper>

或者用java代码(RowBounds)

  • 接口
public interface PeopleMapper {
    List<People> limitRowBounds();
}
  • Mapper.xml
<?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.mybatis.DAO.PeopleMapper">
    <resultMap id="PMap" type="P">
        <result column="id" property="idid"/>
    </resultMap>
    <select id="limitRowBounds" resultMap="PMap">
        select * from mybatis.people;
    </select>
</mapper>
  • 分页java代码
public class PeopleDAOtest {
    @Test
    public void limit01(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        RowBounds bounds = new RowBounds(1, 3);
        PeopleMapper peopleMapper = sqlSession.getMapper(PeopleMapper.class);
        List<People> people = sqlSession.selectList("com.mybatis.DAO.PeopleMapper.limitRowBounds",null,bounds);
        for (People p : people) {
            System.out.println(p);
        }
    }
}

或者用Mybatis插件