MyBatis批量添加數(shù)據(jù)2種實(shí)現(xiàn)方法
1.通過for each標(biāo)簽拼接sql(數(shù)量較少的時(shí)候使用)
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語句(需設(shè)置屬性allowMultiQueries=true)
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true //需設(shè)置屬性jdbc.username=rootjdbc.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進(jìn)行批量添加
先定義一條插入一條記錄的方法
public int addPerson(User user); //接口
<insert parameterType='user'> insert into t_user(username,address) VALUES (#{username},#{address}) </insert>
在java代碼中使用
public void testBatchForExecutor() { SqlSession sqlSession = this.getSqlSessionFactory().openSession(ExecutorType.BATCH); //通過session設(shè)置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(); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. mysql的like模式2. MySQL分區(qū)的優(yōu)點(diǎn)3. 從舊版本SQL Server中重新存儲(chǔ)數(shù)據(jù)4. MYSQL(電話號(hào)碼,身份證)數(shù)據(jù)脫敏的實(shí)現(xiàn)5. mysql啟動(dòng)時(shí)報(bào)錯(cuò) ERROR! Manager of pid-file quit without6. 如何實(shí)現(xiàn)MySQL數(shù)據(jù)庫的備份與恢復(fù)7. 加密你的Access數(shù)據(jù)庫asp打開方法8. 什么是Access數(shù)據(jù)庫9. Oracle根據(jù)逗號(hào)拆分字段內(nèi)容轉(zhuǎn)成多行的函數(shù)說明10. mysql 視圖操作和存儲(chǔ)過程

網(wǎng)公網(wǎng)安備