MyBatis分页
MyBatis自身提供一种分页的方式,不过是逻辑上的分页,先把所有的结果都查出来之后,再去分页,如果在数据量比较大的时候,这种分页方式会效率很低,所以我们要自己设计物理上的分页。
逻辑分页:
public List<Student> findStudent(RowBounds rowbounds);
RowBoundds是MyBatis提供的。
<select id="findStudent" resultMap="StudentResult">
select * from t_student
</select>
在调用该方法前,需要new RowBounds对象。
@Test
public void findStudent() {
logger.info("查找学生详细");
int offset=0;
int limit=3;
RowBounds rowbounds = new RowBounds(offset,limit);
List<Student> studentList = studentMapper.findStudent(rowbounds);
for(Student s:studentList) {
System.out.println(s);
}
}
}
提供了一种重载的构造方法,offset是从哪一个开始,limit是多少个。
我们一般自己写分页,写物理上的分页。
public List<Student> findStudent2(Map<String, Object> map);
我们通过map将分页参数传递过去:
<select id="findStudent2" parameterType="HashMap" resultMap="StudentResult" >
select * from t_student
<if test="#{start}!=null and #{size!=null}">
limit #{start},#{size}
</if>
</select>
调用的时候,填参数就行:
@Test
public void findStudent2() {
logger.info("查找学生详细");
Map<String, Object> map = new HashMap<String,Object>();
map.put("start", 0);
map.put("size", 3);
List<Student> studentList = studentMapper.findStudent2(map);
for(Student s:studentList) {
System.out.println(s);
}
}
缓存
Mybatis 默认情况下,MyBatis 启用一级缓存,即同一个 SqlSession 接口对象调用了相同的 select 语句,则直 接会从缓存中返回结果,而不是再查询一次数据库; 开发者可以自己配置二级缓存,二级缓存是全局的;
默认情况下,select 使用缓存的,insert update delete 是不使用缓存的;
在namespace下配置:
<!--
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"/>
只有当并发量很大的时候,才能看出作用。