MyBatis动态SQL小记

1、select常用标签:

where标签,如果该标签下返回的内容是以AND 或OR 开头的,则它会剔除掉。

不使用where标签:

where

<if test=" id!=null and id!='' ">

id=12345

</if>

<if test=" name!=null and name!='' ">

 and name="张三"

</if>

如果id为空,则if标签返回的就只有 and name="张三" 和前面where连起来:where  and name="张三" 多了and,肯定报错。

而标签<where>下

<where>     

  <if test=" id!=null and id!='' ">

  id=12345

  </if>

  <if test=" name!=null and name!='' ">

   and name="张三"

  </if>

</where>   

如果id为空,则if标签返回的是 and name="张三" 由where 标签删除and加上where得到:where  name="张三" 

 

2、update常用标签

set标签和if标签

如果某项为null不进行更新,保持数据库原值。

update employee

 <set> 

 <if test=" gender!=null and gender!='' ">

  gender=#{gender},

  </if>

  <if test=" name!=null and name!='' ">

   name=#{name}

  </if>    

    </set>

where  id = #{id};   

另,如果name未null ,没有set标签,就多了 个逗号,因此set  的功能:如果该标签下返回的内容是以逗号结尾的,则它会剔除掉。  

 

3、delete常用标签

foreach标签--批量删除

collection 指定要遍历的集合,list类型的参数会特殊处理封装在map中,key就叫list
item 将当前遍历出的元素赋值给指定的变量
separator 每个元素之间的分隔符
open 在遍历出所有的结果之后拼接一个开始的字符串
close 遍历出所有的结果后拼接一个结束的字符
index 索引 遍历list 的时候是索引,遍历map的时候是map的key,item即为当前项的值。
(原文:https://blog.csdn.net/qq_33574890/article/details/78828785 )

举例:
delete   from employee where id in
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">

#{id}

</foreach>
传入参数 int[] ids = {1,2,3,4,5}

 

4、insert常用标签

insert into smbms_user(

<trim suffixOverrides=",">

 <if test=" gender!=null and gender!='' ">

  gender,

  </if>

 <if test=" name!=null and name!='' ">

   name

  </if>  

</trim>

) values(

<trim suffixOverrides=",">

 <if test=" gender!=null and gender!='' ">

 #{gender},

  </if>

  <if test=" name!=null and name!='' ">

   #{name}

  </if>  

</trim>

)

注意:

<trim prefix="WHERE" prefixOverrides="AND|OR">     效果等同于<where>

 <trim prefix="SET" suffixOverrides=",">  效果等同于<set>

 

5、树形查找

比如一个作者对象有多篇文章对象

现有Author类,Article类

一对多情况:Author下有一个列表属性 private List<Article> articleList;

authorMapper.xml   这里把author的id传过去 

<resultMap id="AuthorWithArticles" type="Author">

<id column="id" property="id" jdbcType="VARCHAR" javaType="java.lang.String"/>

<result column="userName" property="userName" jdbcType="VARCHAR" javaType="java.lang.String"/>

<collection property="articleList" column="id"  select="test.mybatis.dao.articleMapper.selectArticleListByAuthorId" />

</resultMap>

在articlemapper.xml有对应的select方法

<select id="selectArticleListByAuthorId" parameterType="java.lang.String" resultType="Author" > 

  select * from

  tb_article where AuthorId=#{Id}

</select>

 

 

更多参考:https://blog.csdn.net/weixin_42608550/article/details/81084091

 

posted @ 2019-04-09 11:28  小纸盒  阅读(193)  评论(0编辑  收藏  举报