MyBatis批量添加數(shù)據(jù)2種實(shí)現(xiàn)方法
1.通過(guò)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語(yǔ)句(需設(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); //通過(guò)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(電話號(hào)碼,身份證)數(shù)據(jù)脫敏的實(shí)現(xiàn)2. MySql導(dǎo)出后再導(dǎo)入數(shù)據(jù)時(shí)出錯(cuò)問(wèn)題3. Oracle的PDB數(shù)據(jù)庫(kù)創(chuàng)建DIRECTORY時(shí)遇到ORA-65254問(wèn)題及解決方法4. MySQL存儲(chǔ)過(guò)程例子(包含事務(wù)、參數(shù)、嵌套調(diào)用、游標(biāo)循環(huán)等)5. Sql Server 2000數(shù)據(jù)庫(kù)日志日益龐大的解決方法6. MySQL decimal unsigned更新負(fù)數(shù)轉(zhuǎn)化為07. mysql-bin.000001文件的來(lái)源及處理方法8. 教你在AIX上安裝IBM DB2 9版本的分區(qū)環(huán)境9. 快速刪除ORACLE重復(fù)記錄10. Fluent Mybatis 批量更新的使用
