MyBatis批量添加、修改和删除
程序员文章站
2024-03-08 23:02:52
废话不多说了,直接步入正题了。
1、批量添加元素session.insert(string string,object o)
public void bat...
废话不多说了,直接步入正题了。
1、批量添加元素session.insert(string string,object o)
public void batchinsertstudent(){ list<student> ls = new arraylist<student>(); for(int i = 5;i < 8;i++){ student student = new student(); student.setid(i); student.setname("maoyuanjun" + i); student.setsex("man" + i); student.settel("tel" + i); student.setaddress("浙江省" + i); ls.add(student); } sqlsession session = sessionfactoryutil.getsqlsessionfactory().opensession(); session.insert("mybatisdemo.domain.student.batchinsertstudent", ls); session.commit(); session.close(); } <insert id="batchinsertstudent" parametertype="java.util.list"> insert into student (id,name,sex,tel,address) values <foreach collection="list" item="item" index="index" separator="," > (#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address}) </foreach> </insert>
2、批量修改session. insert (string string,object o)
实例1:
public void batchupdatestudent(){ list<integer> ls = new arraylist<integer>(); for(int i = 2;i < 8;i++){ ls.add(i); } sqlsession session = sessionfactoryutil.getsqlsessionfactory().opensession(); session.insert("mybatisdemo.domain.student.batchupdatestudent",ls); session.commit(); session.close(); } <update id="batchupdatestudent" parametertype="java.util.list"> update student set name = "5566" where id in <foreach collection="list" item="item" index="index" open="(" separator="," close=")" > #{item} </foreach> </update>
实例2:
public void batchupdatestudentwithmap(){ list<integer> ls = new arraylist<integer>(); for(int i = 2;i < 8;i++){ ls.add(i); } map<string,object> map = new hashmap<string,object>(); map.put("idlist", ls); map.put("name", "mmao789"); sqlsession session = sessionfactoryutil.getsqlsessionfactory().opensession(); session.insert("mybatisdemo.domain.student.batchupdatestudentwithmap",map); session.commit(); session.close(); } <update id="batchupdatestudentwithmap" parametertype="java.util.map" > update student set name = #{name} where id in <foreach collection="idlist" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </update>
3、批量删除session.delete(string string,object o)
public void batchdeletestudent(){ list<integer> ls = new arraylist<integer>(); for(int i = 4;i < 8;i++){ ls.add(i); } sqlsession session = sessionfactoryutil.getsqlsessionfactory().opensession(); session.delete("mybatisdemo.domain.student.batchdeletestudent",ls); session.commit(); session.close(); } <delete id="batchdeletestudent" parametertype="java.util.list"> delete from student where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </delete>
好了,本文到此结束,希望对大家有所帮助。