MySQL進行 批量插入,批量刪除,批量更新,批量查詢
阿新 • • 發佈:2021-06-17
1、批量插入
ServiceImpl層
List<Person> addPeople = new ArrayList<>(); //addPeople存放多個Person物件 personMapper.insetPeopleReturnIds(addPeople);
Dao層介面(這裡的註解param中的list對應xml中的 collection的值, 兩者要保持一致! )
int insetPeopleReturnIds(@Param("list") List<Person> addPeople);
Mapper.xml
(keyColumn是資料庫的欄位,keyProperty對應的是實體類的屬性,為的是讓ID自增長)
<insert id="insetPeopleReturnIds" keyColumn="person_id" keyProperty="personId" parameterType="java.util.List" useGeneratedKeys="true"> insert into person (person_name, id_type, id_num, phone,org_id) values <foreach collection="list" index="index"item="item" separator=","> (#{item.personName,jdbcType=VARCHAR}, #{item.idType,jdbcType=INTEGER}, #{item.idNum,jdbcType=VARCHAR}, #{item.phone,jdbcType=VARCHAR},#{item.orgId,jdbcType=INTEGER}) </foreach> </insert>
2、批量刪除
ServiceImpl層
List<String> list; //list中作者存放的是字串,格式["123","456"] uploadListMapper.deleteByPrimaryUUid(list);
Dao層介面
int deleteByPrimaryUUid(@Param("lists") List<String> list);
Mapper.xml
<delete id="deleteByPrimaryUUid" parameterType="java.util.List"> delete from upload_list where uuid in <foreach close=")" collection="lists" index="index" item="item" open="(" separator=","> #{item,jdbcType=VARCHAR} </foreach> </delete>
3、批量更新
ServiceImpl層
List<Person> oldPeople = new ArrayList<>();//oldPeople存放多個person物件 personMapper.updateBatch(oldPeople);
Dao層介面
int updateBatch(@Param("list") List<Person> list);
Mapper.xml
<update id="updateBatch" parameterType="java.util.List"> update person <trim prefix="set" suffixOverrides=","> <trim prefix="person_name =case" suffix="end,"> <foreach collection="list" index="index" item="item"> when person_id = #{item.personId} then #{item.personName} </foreach> </trim> <trim prefix="id_type =case" suffix="end,"> <foreach collection="list" index="index" item="item"> when person_id = #{item.personId} then #{item.idType} </foreach> </trim> <trim prefix="id_num =case" suffix="end,"> <foreach collection="list" index="index" item="item"> when person_id = #{item.personId} then #{item.idNum} </foreach> </trim> <trim prefix="phone =case" suffix="end,"> <foreach collection="list" index="index" item="item"> when person_id = #{item.personId} then #{item.phone} </foreach> </trim> </trim> where person_id in <foreach close=")" collection="list" item="item" open="(" separator=","> #{item.personId} </foreach> </update>
4、批量查詢
ServiceImpl層
List<String> list; //list中作者存放的是字串,格式["123","456"]
List<UploadList> uploadLists = uploadListMapper.selectByPrimaryUUid(list);
Dao層介面
List<UploadList> selectByPrimaryUUid(@Param("lists") List<String> list);
Mapper.xml
<select id="selectByPrimaryUUid" resultMap="BaseResultMap"> select * from upload_list where uuid in <foreach close=")" collection="lists" index="index" item="item" open="(" separator=","> #{item,jdbcType=VARCHAR} </foreach> </select>