Mybatis常用语法汇总

原文链接:Mybatis常用语法汇总

一、动态sql使用

     1.1、在项目中涉及多个动态查询条件,一般我们是通过 where 1 = 1,这样可以处理where后面对应条件全空的情况,我们可以使用<where>标签,该标签可以自动处理,主要是当我们的sql查询条件以AND和OR结尾时,会自动去除,如

      

<where>  
<if test="keyword != null">  
   and title like concat('%',trim(#{keyword}),'%')   
</if>  
</where>

<where> 
<if test="name != null">  
   or name=#{name} 
</if> 
<if test="keyword != null">  
   or title like concat('%',trim(#{keyword}),'%')   
</if>  
</where>

      1.2、在项目中涉及多个动态update条件时,传统的项目需要我们去除最后一个条件的逗号,但是在mybatis中我们可以使用<set>标签,如

UPDATE user
<set>
    <if test ='null != name'>name = #{name},</if>
    <if test ='null != email'>email = #{email},</if>
    <if test ='null != headUrl'>head_url = #{headUrl},</if>
    <if test ='null != linkData'>link_data = #{linkData},</if>
    <if test ='null != createTime'>create_time = #{createTime},</if>
    <if test ='null != updateTime'>update_time = #{updateTime}</if>
</set>

      1.3、动态if else语句,在mybatis中使用choose、when、otherwise来处理,如下代码

<select id="selectInCondition" parameterType="order" resultType="order">  
      select * from order where amount gt;= #{admount} 
  <choose>
      <when test="merchantId != null">
          and merchant_id = #{merchantId};
      </when>
      <when test="area != 0">
          and area = #{area};
      </when>
      <otherwise>
          or 1 = 1;
      </otherwise>
  </choose>
</select>

二、mybatis大于、小于、等于

       mybatis 中 SQL 写在mapper.xml文件中,而xml解析 < 、>、<=、>= 时会出错,这时应该使用转义写法,如下

<<=>>=&'"
&lt;&lt;=&gt;&gt;=&amp;&apos;&quot;

 

三、mybatis循环标签<foreach>

       3.1、循环查询in语句,代码如下

       

  <select id="findBy" resultMap="BaseResultMap">
    select * from user where user_id in
     <foreach item="item" index="index" collection="list" 
                    open="(" separator="," close=")">
                   #{item}
     </foreach>
 </select>

       3.2、批量插入使用循环,代码如下

<insert id="insertList" parameterType="java.util.List">
          insert into user
          ( name,sex,email,remark)
          values
          <foreach collection="list" item="item" index="index" separator=",">
            (
              #{item.name},
              #{item.sex},
              #{item.email},
              #{item.remark}
            )
             </foreach>   
</insert> 

 

四、重复的sql片段整合在一起使用include标签

定义:
<sql id="Base_Column_List" >  
  id, name, url, priority, logo, img  
</sql>  
引用:
<include refid="Base_Column_List" /> 

五、一对一查询、一对多查询,查看对应博文SpringBoot整合mybatis实现一对一、一对多查询

       

  • 1
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值