package com.admin.common.core.service;

import com.admin.common.utils.uuid.IdUtils;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.MyBatisExceptionTranslator;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

public class BaseService<T> {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;


    public boolean executeBatch(List<T> list, Consumer<T> insert) {
        SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);//跟上述sql区别

        int batchSize = 300;
        try {
            for (int i = 0; i < list.size(); i++) {
                T single = list.get(i);
//                studentInfo.setStudentId(IdUtils.simpleUUID());
                insert.accept(single);
//                studentInfoMapper.saveOrUpdateByStudentNo(studentInfo);
                if (i % batchSize == 0 || i == list.size()) {
                    sqlSession.flushStatements();
                }
            }
            sqlSession.commit();
        } catch (Throwable var11) {
            sqlSession.rollback();
            Throwable unwrapped = ExceptionUtil.unwrapThrowable(var11);
            var11.printStackTrace();
            if (unwrapped instanceof RuntimeException) {
                MyBatisExceptionTranslator myBatisExceptionTranslator = new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true);
                throw (DataAccessException) Objects.requireNonNull(myBatisExceptionTranslator.translateExceptionIfPossible((RuntimeException)unwrapped));
            }
            throw new RuntimeException("插入失败");
        } finally {
            sqlSession.close();
        }
        return true;
    }

}
