package com.cesgroup.service.impl;

import com.cesgroup.entity.Article;
import com.cesgroup.mapper.ArticleMapper;
import com.cesgroup.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by chenpt on 2019/12/2.
 */
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService{

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public List<Article> queryAll(Integer id) {
        return articleMapper.queryAll(id);
    }

    @Override
    public Integer batchAdd(List<Article> list) {
//        return articleMapper.batchAdd(list);//默认写法
        Integer res = 0;
        long time1 = System.currentTimeMillis();
        log.info("*****开始插入*****{}",time1);
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//关闭session的自动提交;
        try {
            res = sqlSession.insert("com.cesgroup.mapper.ArticleMapper.batchAdd", list);
            sqlSession.commit();
        } catch (Exception e){
            log.error("批量插入失败:{}",e);
        }finally {
            sqlSession.close();
        }
        long time2 = System.currentTimeMillis();
        log.info("*****插入结束*****{}",time2);
        log.info("*************累计耗时*************: " + (time2 - time1));
        return res;
    }
}
