Skip to content
BatchService.java 1.24 KiB
Newer Older
cuixiaowei's avatar
cuixiaowei committed
package com.example.demo.mybatis;


import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author shyane
 * @date 2019/12/9
 */
@Service
public class BatchService {
    private SqlSession sqlSession;

    public BatchService(SqlSessionFactory sqlSessionFactory) {
        sqlSession = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
    }

    public int batchInsertCity(List<Entity> entities) {
        EntityMapper entityMapper = sqlSession.getMapper(EntityMapper.class);
        //批量保存执行前时间
        long start = System.currentTimeMillis();
        for (Entity entity : entities) {
            entity.setId(IdUtil.simpleUUID());
            entity.setName("ces");
            entityMapper.insert(entity);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        //批量保存执行后的时间
        Console.log("批量执行时长" + time);
        return cities.size();
    }
}