MyBatis06(分页查询)
目录结构:
配置几乎和前面Mybatis03一样。
mappers不一样:StudentMapper:
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import com.model.Student;
public interface StudentMapper {
public List<Student> findStudents(RowBounds rowBounds);
public List<Student> findStudents2(Map<String,Object> map);
}
StudentMapper.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.mappers.StudentMapper">
<!--
1,size:表示缓存cache中能容纳的最大元素数。默认是1024;
2,flushInterval:定义缓存刷新周期,以毫秒计;
3,eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in first out,先进先出)
4,readOnly:默认值是false,假如是true的话,缓存只能读。
-->
<cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"/>
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="findStudents" resultMap="StudentResult" flushCache="false" useCache="true">
select * from t_student
</select>
<select id="findStudents2" parameterType="Map" resultMap="StudentResult">
select * from t_student
<if test="start!=null and size!=null">
limit #{start},#{size}
</if>
</select>
</mapper>
测试类:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mappers.StudentMapper;
import com.model.Student;
import com.util.SqlSessionFactoryUtil;
public class StudentTest {
private static Logger logger=Logger.getLogger(StudentTest3.class);
private SqlSession sqlSession=null;
private StudentMapper studentMapper=null;
/**
* 测试方法前调用
* @throws Exception
*/
@Before
public void setUp() throws Exception {
sqlSession=SqlSessionFactoryUtil.openSession();
studentMapper=sqlSession.getMapper(StudentMapper.class);
}
/**
* 测试方法后调用
* @throws Exception
*/
@After
public void tearDown() throws Exception {
sqlSession.close();
}
@Test
public void testFindStudent(){
logger.info("查询学生");
//开始为0 每页几条3条
int offset=0,limit=4;
RowBounds rowBounds=new RowBounds(offset,limit);
List<Student> studentList=studentMapper.findStudents(rowBounds);
for(Student student:studentList){
System.out.println(student);
}
}
@Test
public void testFindStudent2(){
logger.info("查询学生");
Map<String,Object> map=new HashMap<String,Object>();
//从第几条开始索引,序号要+1
//显示查询的size大小
map.put("size", 3);
List<Student> studentList=studentMapper.findStudents2(map);
for(Student student:studentList){
System.out.println(student);
}
}
}