为什么分页?
减少数据的处理量
1.使用Limit分页
语法:select *from user limit startIndex,pageSize;
startIndex:起始位置(0开始), pageSize:记录条数
StuMapper.java
public interface StuMapper {
List<Student> selectByLimit(Map<String,Integer> map);
}
StuMapper.xml
这里因为表里字段和数据库字段不匹配,用了结果集映射。
<resultMap id="getSno" type="stu">
<result property="sno" column="sn"/>
</resultMap>
<!--分页 -->
<select id="selectByLimit" resultMap="getSno" parameterType="map">
select * from test.stu limit #{startIndex},#{pageSize}
</select>
StuService.java
这是service层
@Override
public List<Student> selectByLimit(Map<String,Integer> map) {
return stuMapper.selectByLimit(map);
工具类
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resources="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resources);
sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
测试类
@Test
public void LimitTest(){
SqlSession session=MybatisUtils.getSession();
StuMapper mapper = session.getMapper(StuMapper.class);
HashMap<String,Integer>map=new HashMap<String,Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<Student> list = mapper.selectByLimit(map);
for (Student student : list) {
System.out.println(student);
}
session.close();
}
2.RowBounds
StuMapper.java
public interface StuMapper {
List<Student> selectByRowBounds();
}
StuMapper.xml
resultMap是因为字段不匹配,可在上文中查找
<select id="selectByRowBounds" resultMap="getSno">
select * from test.stu
</select>
测试类:
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSession();
RowBounds rowBounds=new RowBounds(0,2);
//通过java代码层面实现分页
List<Student> list = sqlSession.selectList("com.my.mapper.StuMapper.selectByRowBounds",null,rowBounds);
for (Student student : list) {
System.out.println(student);
}
sqlSession.close();
}
结果