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.User;
import com.cesgroup.homwork.mybatis.sample.mapper.UserMapper;
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 li.shangkun
 * @date 2019/12/9
 */
@Service
public class BatchService {
    private SqlSession sqlSession;

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

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