大纲
动态SQL拼接
if 标签的使用
<if test="studentName!=null and studentName!='' "> <!--studentName是字段名-->
</if>
<!-- 进行空字符串校验 -->
foreach 标签的使用
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
<!--
<!-- 传递List,List中是pojo https://www.cnblogs.com/sh086/p/8375791.html
array是类型 array list map set
item : 表示在迭代过程中每一个元素的别名
index :表示在迭代过程中每次迭代到的位置(下标)
使用Map(或Map.Entry对象的集合)时,index将是关键对象,而item将是value对象
-->
<!-- 案例 -->
<select id="dynamicForeachTest" parameterType="java.util.List" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator=","close=")">
#{item}
</foreach>
</select>
choose 标签的使用
<choose>
<when test="studentName!=null and studentName!='' ">
ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')
</when>
<when test="studentSex!= null and studentSex!= '' ">
AND ST.STUDENT_SEX = #{studentSex}
</when>
</choose>
<!-- 可以自动处理第一个and -->
格式化标签
where标签
<where>
<if test="name!=null and name!='' ">
NAME LIKE CONCAT(CONCAT('%', #{name}),'%')
</if>
<if test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</if>
</where>
<!--
替代了where 1=1
如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉
-->
set标签
<update id="updateStudent" parameterType="Object">
UPDATE STUDENT SET
<if test="name!=null and name!='' ">
NAME = #{name},
</if>
<if test="hobby!=null and hobby!='' ">
MAJOR = #{major},
</if>
<if test="hobby!=null and hobby!='' ">
HOBBY = #{hobby}
</if>
WHERE ID = #{id};
</update>
<!--
如果最后的if语句没有生效,会自动剔除末尾if语句中多余的逗号
-->
trim标签
trim属性主要有以下四个
-
prefix:前缀
-
suffix:后缀
-
prefixOverrides:前缀判断的条件
-
suffixOverrides:后缀判断的条件
AND name=#{name} AND hobby=#{hobby}
配置关联关系
association标签
<resultMap type="org.zang.domain.Person" id="personMapper">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<!-- 一对一关联映射:association -->
<association property="card" column="card_id"
select="org.zang.mapper.CardMapper.selectCardById"
javaType="org.zang.domain.Card"/>
</resultMap>
<!-- <association.../>元素来映射一对一的关联关系 -->
<mapper namespace="org.zang.mapper.CardMapper">
<!-- 根据id查询Card,返回Card对象 -->
<select id="selectCardById" parameterType="int" resultType="org.zang.domain.Card">
SELECT * from tb_card where id = #{id}
</select>
</mapper>
collection标签
<!-- 映射Clazz对象的resultMap -->
<resultMap type="org.zang.domain.Clazz" id="clazzResultMap">
<id property="id" column="id"/>
<result property="code" column="code"/>
<result property="name" column="name"/>
<!-- 一对多关联映射:collection fetchType="lazy"表示懒加载 -->
<collection property="students" javaType="ArrayList" column="id" ofType="org.zang.domain.Student"
select="org.zang.mapper.StudentMapper.selectStudentByClazzId" fetchType="lazy">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</collection>
</resultMap>
<!-- <collection.../>元素映射一对多的关联关系 -->