package com.cesgroup.homwork.mybatis.sample.service;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import com.cesgroup.homwork.mybatis.sample.entity.City;
import com.cesgroup.homwork.mybatis.sample.mapper.CityMapper;
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;

/**
 * 批量sql处理类
 * @author ding.haiyang
 * @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<City> cities){
        CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
        //批量保存执行前时间
        long start=System.currentTimeMillis();
        for (City city : cities) {
            city.setId(IdUtil.simpleUUID());
            cityMapper.insert(city);
        }
        long end=  System.currentTimeMillis();
        long time2= end-start;
        //批量保存执行后的时间
        Console.log("批量执行时长"+time2);
        return cities.size();
    }
}
