文章目录
- 动态sql
- 模糊查询
- 查询返回结果集的处理
- 分页
动态sql
BookMapper
xml
bookservice
测试:
MapperSql.test
运行:
模糊查询
BookMapper
BookMapper.xml
Bookservice
StringUtiles
测试:
一共介绍了三种模糊查询的方法,
对比第三种更加实用。
运行:
查询返回结果集的处理
BookMapper
Bookmapper.xml
<select id="List1" resultMap="BaseResultMap">select * from t_mvc_book</select><select id="List2" resultType="com.caoluo.model.Book">select * from t_mvc_book</select><select id="list3" resultType="com.caoluo.model.Book" parameterType="com.caoluo.model.BookVo">select * from t_mvc_book where bid in<foreach collection="bookIds" open="(" close=")" separator="," item="bid">#{bid}</foreach></select><select id="list4" resultType="java.util.Map" parameterType="java.util.Map" >select * from t_mvc_book<where><if test="null != bname and bname !=''">and bname like #{bname}</if></where></select><select id="list5" resultType="java.util.Map" parameterType="java.util.Map">select * from t_mvc_book<where><if test="null != bid and bid !=''">and bid = #{bid}</if></where></select>
</mapper>
BookVo继承Book实体类
测试代码
@Testpublic void list() {//返回resultMap但是使用list<T>
// List<Book> books=this.bookService.List1();//返回的是resulttype使用list<T>接收
// List<Book> books=this.bookService.List2();
// for (Book b :books){
// System.out.print(b);
// }//返回的是resulttype 使用T接收
// BookVo bookVo=new BookVo();
// List list=new ArrayList();
// list.add(5);
// bookVo.setBookIds(list);
// Book book=this.bookService.list3(bookVo);
// System.out.print(book);//返回的是resultType,然后用list<map>进行接收Map map=new HashMap();
// map.put("bname",StringUtils.toLikeStr("李四"));
// List<Map> list=this.bookService.list4(map);
// for (Map m :list){
// System.out.print(m);
// }
// /返回的是resultType,然后用map进行接收map.put("bid",7);Map m=this.bookService.list5(map);System.out.print(m);
分页
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
使用分页插件步奏
1、导入pom依赖
2、Mybatis.cfg.xml配置拦截器
3、使用PageHelper进行分页
4、处理分页结果
Pom依赖
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.2</version>
</dependency>
Mybatis.cfg.xml配置拦截器
<plugins><!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 --><plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
Bookservice层
BookServiceImpl
测试:
运行: