Mybatis CRUD标签使用 模板

C-CREATE 创建

c1-普通insert模板

<insert id="insertUser" parameterType="java.util.Map">

         INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username != null and username != '' ">
                username,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="username != null and username != '' ">
                #{username,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

批量插入

<insert id="add" parameterType="User">
  <foreach collection="list" item="item" index="index" separator=";">
    INSERT INTO TStudent(name,age) VALUES(#{item.name}, #{item.age})
  </foreach>
</insert>

防止重复插入

insert into user(username,age)
select #{username},#{age} 
from user 
where is not exists(select id from user where id = #{id})

R-READ 读取

普通查询模板

 <resultMap id="BaseResultMap" type="com.test.entity.User" >
    <result column="id" property="id" jdbcType="VARCHAR" />
  </resultMap>
 <sql id="BaseList" >
    d.id,
    d.name,
    d.user_id,
    d.username,
  </sql>
  <select id="findUser" resultMap="BaseResultMap">
    select
    <include refid="BaseList" />
    from user d
    WHERE d.user_id= #{userid}
  </select>

普通查询模板二

select
    *
    from user d
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

U-UPDATE 更新

更新模板一

<update id="up"  parameterType="com.test.entity.User">
 UPDATE User
 <trim prefix="set" suffixOverrides=",">
  <if test="username!=null">
  username=#{username},
  </if>
 </trim>
 WHERE id=#{id}
</update>

批量修改

<update id="upList"  parameterType="java.util.List">
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update user
        <set>
            username=${item.username}
        </set>
        where id = ${item.id}
    </foreach>
</update>

D-DELTE 删除

删除模板(不常用 开发中的删除通常为逻辑删除 不做赘述)

<delete id="de" parameterType="java.lang.Integer">
         DELETE FROM
               user
         WHERE
               id = #{id,jdbcType=NUMERIC}
    </delete>

转载于:https://my.oschina.net/u/3022975/blog/1920606

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值