mybatis动态sql
1.1 if
1.2 trim
1.3 foreach
1.4 其他
choose/set/where
动态sql代码展示
<select id="list1" parameterType="com.maven_mybatis.vo.BookVo" resultType="com.zking.maven_mybatis.model.Book">
select
<include refid="Base_Column_List"/>
from t_book where 1=1
<if test="bids != null">
and book_id in
<foreach collection="bids" item="bid" open="(" close=")" separator=",">
#{bid}
</foreach>
</if>
</select>
2.模糊查询(3种方式)
2.1 参数中直接加入%%
2.2 使用${...}代替#{...}(不建议使用该方式,有SQL注入风险)
#{...}与${...}区别?
参数类型为字符串,#会在前后加单引号['],$则直接插入值
1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。
如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by '111',
如果传入的值是id,则解析成的sql为order by "id".
2. $将传入的数据直接显示生成在sql中。
如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,
如果传入的值是id,则解析成的sql为order by id.
3. #方式能够很大程度防止sql注入。
4. $方式无法防止Sql注入。
5. $方式一般用于传入数据库对象,例如传入表名.
6. 一般能用#的就别用$.
注:
mybatis中使用OGNL表达式传递参数 优先使用#{...} ${...}方式存在SQL注入风险
2.3 SQL字符串拼接CONCAT
3.查询返回结果集
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值的数据类型是非自定义的,即jdk的提供的类型
3.1 使用resultMap返回自定义类型集合
3.2 使用resultType返回List<T>
3.3 使用resultType返回单个对象
3.4 使用resultType返回List<Map>,适用于多表查询返回结果集
3.5 使用resultType返回Map<String,Object>,适用于多表查询返回单个结果集
4.分页查询
为什么要重写mybatis的分页?
Mybatis的分页功能很弱,它是基于内存的分页(查出所有记录再按偏移量offset和边界limit取结果),在大数据量的情况下这样的分页基本上是没有用的
4.1 导入分页插件
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
4.2 将pagehelper插件配置到mybatis中
<!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
4.3 在你需要进行分页的Mybatis方法前调用PageHelper.startPage静态方法即可,紧跟在这个方法后的第一个Mybatis查询方法会被进行分页
//设置分页处理
if (null != pageBean && pageBean.isPaginate()) {
PageHelper.startPage(pageBean.getCurPage(), pageBean.getPageRecord());
}
4.4 获取分页信息(二种方式)
4.4.1 使用插件后,查询实际返回的是Page<E>,而非List<E>,Page继承了ArrayList,同时还包含分页相关的信息
Page<Book> page = (Page<Book>)list;
System.out.println("页码:" + page.getPageNum());
System.out.println("页大小:" + page.getPageSize());
System.out.println("总记录:" + page.getTotal());
4.4.2 使用PageInfo
PageInfo pageInfo = new PageInfo(list);
System.out.println("页码:" + pageInfo.getPageNum());
System.out.println("页大小:" + pageInfo.getPageSize());
System.out.println("总记录:" + pageInfo.getTotal());
5.特殊字符处理
>(>)
<(<)
&(&)
空格( )