MyBatis实现分页
通过在映射文件中传入Map类实现
Mapper映射文件
<!-- 查询所有用户 --> <select id="selectAll" parameterType="Map" resultType="User"> select * from user limit #{startIndex}, #{pageSize} </select>
Dao对象
//分页查询 public List<User> getAll(int currentPage, int pageSize) throws IOException { SqlSession session = MyBatisUtil.getSession(); Map<String, Integer> map = new HashMap<String, Integer> (); map.put("startIndex", (currentPage - 1) * pageSize); map.put("pageSize", pageSize); List<User> list = session.selectList("com.eric.entity.UserMapper.selectAll", map); session.close(); return list; }
通过RowBounds实现
- Mapper文件不需要改变
- Dao需要新建RowBounds对象:
RowBounds(startIndex, pageSize)
public List<User> getAll(int currentPage, int pageSize) throws IOException { SqlSession session = MyBatisUtil.getSession(); RowBounds rowBounds = new RowBounds((currentPage - 1) * pageSize, pageSize); List<User> list = session.selectList("com.eric.entity.UserMapper.getAll", null, rowBounds); session.close(); return list; }