1. 程式人生 > >mybatis -- 動態sql增刪改

mybatis -- 動態sql增刪改

<!-- ============================ 動態查詢 =================================== -->
<!-- 
   <where>用於動態條件組合查詢,可以去掉where後的第一個and
 -->
<select id="selectPersonByCondition" parameterType="qc" resultMap="BaseResultMap">
   select * from person t
   <where>
      <if test
="name != null">
t.name like '%${name}%' </if> <if test="gender != null"> and t.gender = #{gender} </if> <if test="personAddr != null"> and t.person_addr like '%${personAddr}%' </if> <if test="birthday != null"
>
<![CDATA[ and t.birthday < #{birthday} ]]> </if> </where> </select> <!-- ============================ 動態修改 =================================== --> <!-- <SET>能處理掉最後一個逗號,不要忘記加上t.person_id = #{personId}, t.person_id = #{personId}:無其他屬性修改,防止sql拼接出錯 -->
<update id="dynamicUpdate" parameterType="person"> update person t <set> t.person_id = #{personId}, <if test="name != null"> t.name = #{name}, </if> <if test="gender != null"> t.gender = #{gender}, </if> <if test="personAddr != null"> t.person_addr = #{personAddr}, </if> <if test="birthday != null"> t.birthday = #{birthday} </if> </set> where t.person_id = #{personId} </update> <!-- ============================ 多個Id 查詢 =================================== --> <!-- (1,2,3) map.put("ids", Integer[]) foreach遍歷集合來組裝sql collection:map中集合的key open:以某種字元開始 close:以某種字元結束 item:集合中的元素 separator:以某種字元分隔 index:當前遍歷到的索引號 --> <select id="selectPersonByIn" parameterType="map" resultMap="BaseResultMap"> select * from person t where t.person_id in <foreach collection="ids" open="(" close=")" item="personId" separator="," index="index"> #{personId} </foreach> </select> <!-- ============================ 多條資料刪除 =================================== --> <delete id="deleteBatch" parameterType="map"> delete from person where person_id in <foreach collection="ids" open="(" close=")" item="personId" separator="," index="index"> #{personId} </foreach> </delete> <!-- ============================ 多條資料 新增 =================================== --> <!-- 太多記憶體溢位(分批) map.put("personList", List<Person> list) insert into person(id, name)values(1, 'zhansan'),(2, 'lisi'),... selectKey : 返回主建Id --> <insert id="insertBatch" parameterType="map"> <selectKey keyProperty="personId" order="AFTER" resultType="int"> select LAST_INSERT_ID() </selectKey> insert into person (person_id, name, gender, person_addr, birthday) values <foreach collection="personList" separator="," item="person"> (#{person.personId}, #{person.name}, #{person.gender}, #{person.personAddr}, #{person.birthday}) </foreach> </insert> ------------------------ 增刪查 - 記憶體溢位處理方法 ---------------- if(i%100 == 0){ map.put("personList", pList); session.insert("com.rl.mapper.PersonMapper.insertBatch", map); pList.clear(); } } //迴圈外 map.put("personList", pList); session.insert("com.rl.mapper.PersonMapper.insertBatch", map);