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>
相關文章
相關標籤/搜索