mybatis中分頁有3種方式來實現,通過sql語句(兩種傳參方式)來實現,通過mybatis 的 Rowbounds 來實現。
通過(自定義類型)傳參 來實現分頁:
映射文件:
1
2
3
|
< select id= "findListBypage" parameterType= "cn.wh.util.PageUtil" resultType= "Role" > select * from t_role limit #{ index },#{ size } </ select > |
測試代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 通過自定義類型來傳參 實現分頁功能 需要新建一個類型 */ @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傳參實現:
映射文件:
1
2
3
|
<select id= "findListBypage" parameterType= "map " resultType= "Role" > select * from t_role limit #{index},#{size} </select> |
測試代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 可以通過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來實現分頁:
映射文件:
1
2
3
|
<select id= "findAll" resultType= "Role" > select * from t_role </select> |
測試代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 使用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 傳參來實現分頁
模糊查詢
映射文件:
1
2
3
|
<select id= "selectLike" parameterType= "string" resultType= "Role" > select *from t_role where name like #{name} </select> |
測試代碼:
1
2
3
4
5
6
7
8
9
10
|
/** * 模糊查詢 */ @Test public void testLike1(){ List<Role> list = session.selectList( "cn.wh.mapper.RoleMapper.selectLike" , "%會員" ); for (Role r:list){ System.out.println(r.getName()); } } |
第二種方式:
1
2
3
|
< select id = "selectLike1" parameterType = "string" resultType = "Role" > select *from t_role where name like concat(#{name},'%'); </ select > |
測試代碼:
1
2
3
4
5
6
7
8
9
10
|
/** * 模糊查詢 */ @Test public void testLike2(){ List<Role> list = session.selectList( "cn.wh.mapper.RoleMapper.selectLike1" , "黃" ); for (Role r:list){ System.out.println(r.getName()); } } |
注意:通常使用第二種方式實現模糊查詢
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。