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.MyEntity;
import com.cesgroup.homwork.mybatis.sample.mapper.MyEntityMapper;
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;
@Service
public class BatchService {
    private SqlSession sqlSession;

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

    public int batchInsertCity(List<MyEntity> cities){
        MyEntityMapper myEntityMapper = sqlSession.getMapper(MyEntityMapper.class);
        //批量保存执行前时间
        long start=System.currentTimeMillis();
        for (MyEntity MyEntity : cities) {
            MyEntity.setId(IdUtil.simpleUUID());
            myEntityMapper.insert(city);
        }
        long end=  System.currentTimeMillis();
        long time2= end-start;
        //批量保存执行后的时间
        Console.log("批量执行时长"+time2);
        return cities.size();
    }
}
