MyBatis批量添加數(shù)據(jù)2種實現(xiàn)方法
1.通過for each標簽拼接sql(數(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語句(需設置屬性allowMultiQueries=true)
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true //需設置屬性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進行批量添加
先定義一條插入一條記錄的方法
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設置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(); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. DB2 與 Microsoft SQL Server 2000 之間的 SQL 數(shù)據(jù)復制2. 細化解析:Oracle 10g ASM 的一點經(jīng)驗3. DB2 XML 全文搜索之為文本搜索做準備4. MyBatis中$和#的深入講解5. 國內學院派專家對DB2 9新產(chǎn)品贊不絕口6. 解讀Oracle中代替like進行模糊查詢的方法instr(更高效)7. MySQL Shell的介紹以及安裝8. 使用 Database Access(數(shù)據(jù)庫訪問)組件9. MySQL中庫的基本操作指南(推薦!)10. Mybatis 自動映射(使用需謹慎)

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