一、为什么要分页
减少数据的处理量
二、limit分页
# startIndex, pageSize
select * from mybatis.user limit 0, 1
//User实体类
public class User {
int id;
String name;
String pwd;
public User() {}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
limit分页实现
//UserMapper接口
public interface UserMapper {
//limit分页
List<User> getUserByLimit(Map<String, Object> map);
}
<?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">
<!-- namespace=绑定一个对应的Dao/Mapper接口 -->
<!-- 等同于JDBC中的UserDaoImpl(接口实现类),转变为Mapper配置文件 -->
<mapper namespace="com.comprehensive.dao.UserMapper">
<!-- limit分页 -->
<select id="getUserByLimit" parameterType="map" resultType="com.comprehensive.pojo.User">
select * from mybatis.user limit #{startIndex}, #{pageSize}
</select>
</mapper>
//测试类
public class UserMapper_Test {
@Test
//limit分页
public void test3() {
SqlSession sqlSession = MyBatis_Util.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("startIndex", 0);
map.put("pageSize", 1);
for(User user : mapper.getUserByLimit(map)) System.out.println(user);
sqlSession.close();
}
}
三、RowBounds分页
public interface UserMapper {
//RowBounds分页
List<User> getUserByRowBounds();
}
<?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">
<!-- namespace=绑定一个对应的Dao/Mapper接口 -->
<!-- 等同于JDBC中的UserDaoImpl(接口实现类),转变为Mapper配置文件 -->
<mapper namespace="com.comprehensive.dao.UserMapper">
<!-- RowBounds分页 -->
<select id="getUserByRowBounds" resultType="com.comprehensive.pojo.User">
select * from mybatis.user
</select>
</mapper>
public class UserMapper_Test {
@Test
//RowBounds分页
public void test4() {
//该方式是通过Java代码实现
SqlSession sqlSession = MyBatis_Util.getSqlSession();
List<User> userList = sqlSession.selectList("com.comprehensive.dao.UserMapper.getUserByRowBounds",
null, new RowBounds(0, 1));
for(User user : userList) System.out.println(user);
sqlSession.close();
}
}