MyBatis动态SQL小记

一、select经常使用标签:java

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

不使用where标签:mybatis

whereapp

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

id=12345spa

</if>.net

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

 and name="张三"对象

</if>blog

若是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="张三" 

 

二、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  的功能:若是该标签下返回的内容是以逗号结尾的,则它会剔除掉。  

 

三、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}

 

四、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>

 

五、树形查找

好比一个做者对象有多篇文章对象

现有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

相关文章
相关标签/搜索