本文根据本人项目中实际所见频率排出顺序,持续更新调整,新手向,欢迎同学们指出问题
目录
1.<if ></if>
3.<foreach > </foreach>
4.<include>
5. <sql id=""></sql>
1.<if ></if>
如果if中条件的条件成立,则sql会拼加上<if ></if>里面的部分,如果在where后不能直接拼,需要加一个 1=1 也就是true
<select id="selectUseIf" parameterType="com.soft.test.model.DynamicTestModel" resultMap="userMap">
select * from t_user where 1=1
<if test='id != null'>
and id=#{id}
</if>
</select>
2.<![CDATA[]]>
被<![CDATA[]]>
这个标记所包含的内容将表示为纯文本,比如<![CDATA[<]]>
表示文本内容“<”
。
此标记用于xml文档中,我们先来看看使用转义符的情况。我们知道,在xml中,”<”
、”>”
、”&”
等字符是不能直接存入的,否则xml语法检查时会报错,如果想在xml中使用这些符号,必须将其转义为实体,如”<”
、”>”
、”&”
,这样才能保存进xml文档。
在使用程序读取的时候,解析器会自动将这些实体转换回”<”
、”>”
、”&”
。举个例子:
<age> age < 30 </age>
上面这种写法会报错,应该这样写:
<age> age < 30 </age>
举例:查找时间段
<if test="infoTemplateAll.createTimeEnd != null">
<![CDATA[ AND create_time <= #{infoTemplateAll.createTimeEnd}]]>
</if>
3.<foreach > </foreach>
foreach元素的属性主要有item,index,collection,open,separator,close。
- item:集合中元素迭代时的别名,该参数为必选。
- index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
- open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
- separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
- close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
- collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
举例
<if test="infoTemplateAll.templateTypes != null and infoTemplateAll.templateTypes.size() > 0">
AND template_type IN
<foreach collection="infoTemplateAll.templateTypes" separator="," index="index" item="item"
open="(" close=")">
#{infoTemplateAll.templateTypes[${index}]}
</foreach>
</if>
4.<include>
MyBatis中sql标签定义SQL片段,
include标签引用,可以复用SQL片段
sql标签中id属性对应include标签中的refid属性。通过include标签将sql片段和原sql片段进行拼接成一个完整的sql语句进行执行。
<sql id="sqlid">
res_type_id,res_type
</sql>
<select id="selectbyId" resultType="com.property.vo.PubResTypeVO">
select
<include refid="sqlid"/>
from pub_res_type
</select>
- 引用公用的sql片段
<include refid="namespace.sqlid"/>
include标签中也可以用property标签,用以指定自定义属性。在sql标签中通过${}取出对应的属性值。
<select id="queryPubResType" parameterType="com.property.vo.PubResTypeVO" resultMap="PubResTypeList">
select a.res_type_id,
<include refid="com.common.dao.FunctionDao.SF_GET_LNG_RES_TYPE">
<property name="AI_RES_TYPE_ID" value="a.res_type_id"/>
<property name="lng" value="#{lngId}"/>
<property name="female" value="'女'"/>
</include> as res_type
from pub_res_type a
</select>
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。
resultMap:适合使用返回值是自定义实体类的情况
resultType:适合使用返回值得数据类型是非自定义的,即jdk的提供的类型
5.<sql id=""></sql>
MyBatis中sql标签定义SQL片段,
include标签引用,可以复用SQL片段
<sql id="sqlid">
res_type_id,res_type
</sql>
借鉴博文