MyBatis批量添加数据2种实现方法
程序员文章站
2022-05-26 09:59:38
1.通过for each标签拼接sql(数量较少的时候使用) a.拼接values() public int addpersons(@param("persons") list
1.通过for each标签拼接sql(数量较少的时候使用)
a.拼接values()
public int addpersons(@param("persons") list<person> persons);//接口
<insert id="addpersons"> insert into person(username,email,gender) values <foreach collection="persons" item="person" separator=";"> (#{person.username},#{person.email},#{person.gender}) </foreach> </insert> <!--类似的效果 insert into person(username,email,gender) values("zhangsan","zhangsan@163.com","f"),("lisi","lisi@163.com","f"),... -->
b.拼接insert sql语句(需设置属性allowmultiqueries=true)
jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowmultiqueries=true //需设置属性
jdbc.username=root
jdbc.password=123
public int addpersons(@param("persons") list<person> persons);//接口
<insert id="addpersons"> insert into person(username,email,gender) values <foreach collection="persons" item="person" separator=","> (#{person.username},#{person.email},#{person.gender}) </foreach> </insert> <!--类似的效果 insert into person(username,email,gender) values("tom","zhangsan@163.com","f"); insert into person(username,email,gender) values("jerry","lisi@163.com","f");...-->
2.基于session的executortype进行批量添加
先定义一条插入一条记录的方法
public int addperson(user user); //接口
<insert id="addperson" parametertype="user"> insert into t_user(username,address) values (#{username},#{address}) </insert>
在java代码中使用
public void testbatchforexecutor() { sqlsession sqlsession = this.getsqlsessionfactory().opensession(executortype.batch); //通过session设置executortype开启批量添加,类似jdbc的addbatch操作 personmapper personmapper = sqlsession.getmapper(personmapper.class); for (int i = 0; i <10000 ; i++) { personmapper.addperson(new user("jerry","bj")); } sqlsession.commit(); sqlsession.close(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读