mybatis xml sql 语句的常用语句

 

1:提取公共的sql语句:

2:动态添加----sql语句:

代码:

  <insert id="test1" parameterType="com.floor.shop.model.Product">
        INSERT INTO product
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="productName!=null and productName!=''">
                product_name,
            </if>
            <if test="stockNum!=null and stockNum!=''">
                stock_num,
            </if>
            <if test="salePrice!=null and salePrice!=''">
                sale_price,
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">

            <if test="productName!=null and productName!=''">
                #{productName},
            </if>
            <if test="stockNum!=null and stockNum!=''">
                #{stockNum},
            </if>
            <if test="salePrice!=null and salePrice!=''">
                #{salePrice},
            </if>

        </trim>
    </insert>
View Code

3:动态修改----sql语句:

4:增加前避免重复:

(当userName在数据库中不存在的情况下,增加到数据库)

5:修改或者新增获取受影响的行数:

6:新增自动获取主键(新增id):

7:dao多参数处理,不封装的情况下传递参数:

mapper中的sql语句不用添加参数类型(paramater=" ")

8:传入多个值的数组处理(foreach):

 接口:

映射文件:

测试:

批量新增,数据采用list传入:

<insert id="saveCustomerOpenBankInfo" parameterType="List">
    INSERT INTO resource_customer_openbank(id,open_name,account_number,open_bank,customer_id)
    VALUES
     <foreach item="item" collection="list" index="idx" open="" separator="," close="">
    (#{item.id}, #{item.openName}, #{item.accountNumber},#{item.openBank},#{item.customerId})
     </foreach>
</insert>

批量插入去重数据:

<!--插入用户角色信息  -->

    <insert id="insertUserRole" parameterType="ArrayList" >
    insert into usi_user_role (user_id,role_id)
    <foreach collection="list" item="item" index="index" separator="union all">
    select #{item.userid,jdbcType=VARCHAR},
    #{item.roleid,jdbcType=VARCHAR} from dual  where not exists(select * from usi_user_role
     where user_id = #{item.userid,jdbcType=VARCHAR}
       and role_id = #{item.roleid,jdbcType=VARCHAR})
    </foreach>

  </insert> 

mybatis like 拼接、动态sql拼接:

1、CONCAT()拼接%:

 SELECT * FROM t_usr WHERE name like CONCAT('%',#{name},'%') 

2:bind:

 SELECT  *  
  FROM t_usr 
  WHERE
      <if test="name !=null || name !=''">
          <bind name="name" value="'%' + name + '%'"/>
          name like #{name}
      </if>

 

 

原文地址:https://www.cnblogs.com/dw3306/p/9289891.html