发布于 2017-08-26 21:36:08 | 189 次阅读 | 评论: 0 | 来源: 网友投递
MyBatis 基于Java的持久层框架
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
mybatis中分页有3种方式来实现,通过sql语句(两种传参方式)来实现,通过mybatis 的 Rowbounds 来实现。
通过(自定义类型)传参 来实现分页:
映射文件:
<select id="findListBypage" parameterType="cn.wh.util.PageUtil" resultType="Role">
select * from t_role limit #{index},#{size}
</select>
测试代码:
/**
* 通过自定义类型来传参 实现分页功能 需要新建一个类型
*/
@Test
public void testPage1(){
PageUtil pu = new PageUtil();
pu.setIndex(3);
pu.setSize(3);
List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", pu);
for(Role r:list){
System.out.println(r.getName());
}
}
通过map传参实现:
映射文件:
<select id="findListBypage" parameterType="map " resultType="Role">
select * from t_role limit #{index},#{size}
</select>
测试代码:
/**
* 可以通过map来传参 这样可以不用新建新的类型
*/
@Test
public void testPage2(){
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("index", 0);
map.put("size", 3);
List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", map);
for(Role r:list){
System.out.println(r.getName());
}
}
通过RowBounds来实现分页:
映射文件:
<select id="findAll" resultType="Role">
select * from t_role
</select>
测试代码:
/**
* 使用rowBounds来实现分页
*/
@Test
public void testPage3(){
//第一个参数 是index,开始下标
//第二个参数 是size,每页显示记录数
RowBounds bounds = new RowBounds(3, 3);
List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findAll", null,bounds);
for(Role r:list){
System.out.println(r.getName());
}
}
注意:通常情况下使用 Map 传参来实现分页
模糊查询
映射文件:
<select id="selectLike" parameterType="string" resultType="Role">
select *from t_role where name like #{name}
</select>
测试代码:
/**
* 模糊查询
*/
@Test
public void testLike1(){
List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike","%会员");
for(Role r:list){
System.out.println(r.getName());
}
}
第二种方式:
<select id="selectLike1" parameterType="string" resultType="Role">
select *from t_role where name like concat(#{name},'%');
</select>
测试代码:
/**
* 模糊查询
*/
@Test
public void testLike2(){
List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike1","黄");
for(Role r:list){
System.out.println(r.getName());
}
}
注意:通常使用第二种方式实现模糊查询
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHPERZ。