版权声明:如果转载或使用本博客,请标明出处 https://blog.csdn.net/Black1499/article/details/83501248
1、概述
MyBatis最为强大的部分是提供了动态SQL的支持,一些查询逻辑可以直接在xml中完成,大大简化了我们的操作,体现出了MyBatis的灵活性、拓展性、和可维护性。
MyBatis中的四大动态SQL元素:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
2、使用
if元素
if元素是我们最为常用的判断语句,test属性相当于条件,使用起来也十分简单。
<select id="queryByNameAndCity" resultType="com.lzx.entity.Author">
select * from author where 1=1
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="city != null and city != ''">
and city = #{city}
</if>
</select>
choose、when、otherwise元素
当条件较多时,很明显我们使用if元素就不是那么合适。MyBatis给我们提供了类似java中的switch…case…default语句,即choose…when…otherwise
<select id="queryByNameAndCity" resultType="com.lzx.entity.Author">
select * from author where 1=1
<choose>
<when test="name != null and name != ''">
and name = #{name}
</when>
<otherwise>
and city is not null
</otherwise>
</choose>
</select>
trim, where, set元素
回到最初的if元素中,我们会发现如果所有的条件都不成立,那么条件"1=1"就十分奇怪,在这里我们可以使用where元素进行修改
<select id="queryByNameAndCity" resultType="com.lzx.entity.Author">
select * from author
<where>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="city != null and city != ''">
and city = #{city}
</if>
</where>
</select>
有些时候我们需要去掉一些特殊的SQL语句,比如and、or,这个时候我们可以使用trim元素。trim元素意味着去掉一些字符串,prefix代表的是语句的前缀,prefixOverrides代表的是需要去掉的字符串。
<select id="queryByName" resultType="com.lzx.entity.Author">
select * from author
<trim prefix="where" prefixOverrides="and">
<if test="name != null and name != ''">
and name = #{name}
</if>
</trim>
</select>
set元素,我们常用到更新语句中
<update id="updateAuthor">
update author
<set>
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="city != null and city != ''">
city = #{city}
</if>
</set>
where id = #{id}
</update>
foreach元素
foreach是一个循环语句,他的作用是遍历集合,支持数组和集合。我们可以用来批量删除或者批量添加。
- collection元素是传过来的集合名
- item是循环中的元素
- index是当前元素的下标
- open和close代表使用什么符号包括这些集合元素
- separator是各元素的间隔符
<insert id="insertAuthor">
insert into author values
<foreach collection="authorList" index="id" item="author" separator=",">
(#{name},#{city})
</foreach>
</insert>
<delete id="deleteAuthor">
delete author where id in
<foreach collection="id" index="index" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
blind元素
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。
<select id="queryByNameAndCity" resultType="com.lzx.entity.Author">
<blind name="a_name" value="'%' + name + '%'"/>
<blind name="a_name" value="'%' + city + '%'"/>
select * from author where name = #{a_name} and city = #{a_city}
</select>