1. 程式人生 > >mybatis中的三種 批量操作資料的方法

mybatis中的三種 批量操作資料的方法

方法1:

使用for迴圈在java程式碼中insert (不推薦)

方法2:

使用在Mapper.xml當中使用 foreach迴圈的方式進行insert

PersonDao.java檔案

public interface PersonDao {
    
	//這個是使用 foreach方式的mybatis 批量操作 
	public void batchInsert(@Param("list")List<Person>list);

}

PersonDao.xml

	<insert id="batchInsert" >
 		insert into person (
 			id,
			person_name,
			birthday,
			address,
			age,
			gender	
 		)
 		values
 		<foreach collection="list" item="list" index="index" separator="," >
 		(
 			#{list.id},
 			#{list.person_name},
 			#{list.birthday},
			#{list.address},
			#{list.age},
			#{list.gender}	
 		)
 		</foreach>
 	</insert>

主測試函式:
public static void main5(String[] args) throws Exception {
		SqlSession session = getSqlSession();
		
		PersonDao pd = session.getMapper( PersonDao.class );
	
		List<Person>pl = new ArrayList<Person>();
		Person p1 = new Person(); p1.setPerson_name("哈哈哈吧");   p1.setAddress("深圳"); p1.setBirthday(new Date());
		Person p2 = new Person(); p2.setPerson_name("您好");  p2.setAddress("上海"); p2.setBirthday(new Date());
		Person p3 = new Person(); p3.setPerson_name("我是張偉");  p3.setAddress("廣州"); p3.setBirthday(new Date());
		pl.add(p1);
		pl.add(p2);
		pl.add(p3);
		
		pd.batchInsert(pl);
		
		System.out.println("完成batchInsert");
		
		session.commit();
		
		session.close();
		//pd.batchInsert( pl );
	}
	

方法3:
Mybatis內建的 ExecutorType有三種,預設是Simple,該模式下它為每個語句的執行建立一個新的預處理語句,

單條提交sql,而batch模式 重複使用已經預處理的語句,並且批量執行所有更新語句,顯然 batch的效能更優,

中間在提交的過程中還可以設定等待時間,避免資料庫壓力過大。

public static void main(String[] args) throws Exception {
		
		InputStream in = new FileInputStream( "F:\\myeclipse_workspace\\mybatisGeneratortest\\src\\test\\resources\\mybatis-config.xml");
		SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
		SqlSessionFactory factory = ssfb.build(in);
		
		SqlSession session = factory.openSession( ExecutorType.BATCH,false );
		
		PersonDao pd = session.getMapper( PersonDao.class );
		
		int size = 100000;
		
		try {
			
			for(int i=0;i<size;i++){
				Person p = new Person();
				p.setPerson_name("小明"); p.setBirthday(new Date());
				pd.insertPeron(p);
				if( i % 100 == 0 || i == size - 1 ){ //加上這樣一段程式碼有好處,比如有100000條記錄,每超過 100 條提交一次,中間等待10ms,可以避免一次性提交過多資料庫壓力過大
					session.commit();
					session.clearCache();
					Thread.sleep(10);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}