Two ways of mybatis batch insert

1. Mybiats foreach tag

The main use of foreach is to build in conditions, which can iterate over a collection in a SQL statement. The attributes of the foreach element mainly include item, index, collection, open, separator, and close. item represents the alias of each element in the collection when iterating, index specifies a name, which is used to represent the position of each iteration during the iteration process, open represents what the statement starts with, and separator represents between each iteration What symbol is used as a delimiter, close means what to end with, the most critical and error-prone when using foreach is the collection attribute, which must be specified, but in different cases, the value of this attribute is different. Yes, there are three main situations:

  1. If a single parameter is passed in and the parameter type is a List, the value of the collection attribute is list
  2. If a single parameter is passed in and the parameter type is an array array, the property value of collection is array
  3. If the incoming parameters are multiple, we need to encapsulate them into a Map
The specific usage is as follows:
<insert id="insertBatch" parameterType="List">
        INSERT INTO TStudent(name,age)
	<foreach collection="list" item="item" index="index" open="("close=")"separator="union all">
	    SELECT #{item.name} as a, #{item.age} as b FROM DUAL
	</foreach>
</insert>

二、mybatis ExecutorType.BATCH

There are three built-in ExecutorTypes in Mybatis. The default is simple. In this mode, it creates a new prepared statement for the execution of each statement and submits sql in a single line; while the batch mode reuses the preprocessed statements and executes all of them in batches. Update statement, obviously batch performance will be better; but batch mode also has its own problems, for example, during Insert operation, before the transaction is committed, there is no way to obtain the self-incrementing id, which is not in line with the business in certain situations. required

The specific usage is as follows:

*Method one of spring+mybatis

//获取sqlsession
//从spring注入原有的sqlSessionTemplate
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
// 新获取一个模式为BATCH,自动提交为false的session
// 如果自动提交设置为true,将无法控制提交的条数,改为最后统一提交,可能导致内存溢出
SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false);

    //通过新的session获取mapper
    fooMapper = session.getMapper(FooMapper.class);
    int size = 10000;
    try{
        for(int i = 0; i < size; i++) {
            Foo foo = new Foo();
            foo.setName(String.valueOf(System.currentTimeMillis()));
        //session.insert("com.xx.mapper.UserMapper.insert",foo);
  //session.update("com.xx.mapper.UserMapper.updateByPrimaryKeySelective",foo);
           // session.insert(“包名+类名", foo);
            fooMapper.insert(foo); //这里要么是用session那样去新建,要么是用新获取的mapper
            if(i % 1000 == 0 || i == size - 1) {
             //手动每1000个一提交,提交后无法回滚 
            session.commit();
            //清理缓存,防止溢出
            session.clearCache();
            }
        }
    } catch (Exception e) {
        //没有提交的数据可以回滚
        session.rollback();
    } finally{
        session.close();
    }
    
  • spring+mybatis

Method Two:

Combined with the general mapper sql alias, the best package name + class name

public void insertBatch(Map<String,Object> paramMap, List<User> list) throws Exception {
		// 新获取一个模式为BATCH,自动提交为false的session
		// 如果自动提交设置为true,将无法控制提交的条数,改为最后统一提交,可能导致内存溢出
		SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
		try {
			if(null != list || list.size()>0){
				int  lsize=list.size();
				for (int i = 0, n=list.size(); i < n; i++) {
					User user= list.get(i);
					user.setIndate((String)paramMap.get("indate"));
					user.setDatadate((String)paramMap.get("dataDate"));//数据归属时间
				//session.insert("com.xx.mapper.UserMapper.insert",user);
  //session.update("com.xx.mapper.UserMapper.updateByPrimaryKeySelective",_entity);
                                        session.insert(“包名+类名", user);
					if ((i>0 && i % 1000 == 0) || i == lsize - 1) {
						// 手动每1000个一提交,提交后无法回滚
						session.commit();
						// 清理缓存,防止溢出
						session.clearCache();
					}
				}
			}
		} catch (Exception e) {
			// 没有提交的数据可以回滚
			session.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	} 

========== After testing, the above is still correct. Mainly session.insert("package name + class name", user); This must be set correctly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325958860&siteId=291194637