1、大于号、小于号在sql语句中的转换
使用mybatis 时sql语句是写在xml文件中,如果sql中有一些特殊的字符的话,比如< ,<=,>,>=等符号,会引起xml格式的错误,需要替换掉,或者不被转义。
有两种方法可以解决:转义字符和标记CDATA块。
方式1、转义字符
1 <select id="searchByPrice" parameterType="Map" resultType="Product"> 2 <!-- 方式1、转义字符 --> 3 select * from Product where price >= #{minPrice} and price <= #{maxPrice} 4 </select>
方式2、标记CDATA
1 <select id="searchByPrice" parameterType="Map" resultType="Product"> 2 <!-- 方式2、CDATA --> 3 <![CDATA[select * from Product where price >= #{minPrice} and price <= #{maxPrice} ]]> 4 </select>
转义字符表
转义 | 符号 |
---|---|
< |
< |
> |
> |
& |
& |
' |
’ |
" |
“ |
2、MyBatis中的resultType和resultMap
网上的总结很多,简单而言,resultType用于返回值只有一个字段的类型,resultMap用于返回值有多个字段的类型。至于结果是List还是一个,则在Mapper中定义返回值是List还是单个。
使用resultType:
1 <select id="count" resultType="java.lang.Integer"> 2 SELECT count(*) FROM USER 3 </select>
使用resultMap:
1 <resultMap type="com.liulanghan.Blog" id="BlogResult"> 2 <id column="id" property="id"/> 3 <result column="title" property="title"/> 4 <result column="content" property="content"/> 5 <result column="owner" property="owner"/> 6 </resultMap> 7 8 <select id="selectBlog" parameterType="int" resultMap="BlogResult"> 9 select * from t_blog where id = #{id} 10 </select>
3、参数
Mapper中需要用@Param("queryDate")定义参数名称,sql中用#{queryDate}使用参数,字符串也不需要引号。
参数判断和if的用法:
1 <if test="queryDate != null"> 2 and queryDate >= #{queryDate} 3 </if>
when otherwise就是if else
1 <choose> 2 <when test="isDelete != null and isDelete == 0"> 3 isDelete=0 4 </when> 5 <otherwise> 6 isDelete=1 7 </otherwise> 8 </choose>
如果要判断的字符串,则需要加引号
1 <when test="gender != null and gender == 'MALE'"> 2 gender='MALE' 3 </when>