import com.ces.mapper.BlogMapper;
import com.ces.pojo.Blog;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.io.IOException;
import java.util.*;

/**作业*/
public class MybatisTest {
    SqlSession sqlSession;
    SqlSessionFactory sqlSessionFactory;
    @Before
    public void init() throws IOException {
        sqlSessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis/mybatis-config.xml"));
        sqlSession = sqlSessionFactory.openSession();
    }
    /**作业*/
    @Test
    public void testLogIntercept(){
        BlogMapper blogMapper=sqlSession.getMapper(BlogMapper.class);
        blogMapper.selectOne(1000L,"b14ffbdc-c3ac-4b84-afb6-2bba3a1636bd");
        //执行结果
        /**sql语句 ：select id,name,update_time,create_time from blog where id=? and name=?
        ==>param1 :1000  param2 :b14ffbdc-c3ac-4b84-afb6-2bba3a1636bd
        执行sql ：select id,name,update_time,create_time from blog where id=1000 and name="b14ffbdc-c3ac-4b84-afb6-2bba3a1636bd"
        执行结果 ：[Blog(name=b14ffbdc-c3ac-4b84-afb6-2bba3a1636bd, id=1000, createTime=Sun Dec 29 23:32:04 CST 2019, updateTime=Sun Dec 29 23:32:04 CST 2019)]
        执行时间为49ms
         **/
    }

    /**插入测试数据到数据库*/
    @Test
    @Ignore
    public void testBatch(){
        SqlSession batchSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        BlogMapper batchSessionMapper = batchSession.getMapper(BlogMapper.class);
        List<Blog> list=new ArrayList<Blog>(100);
        /**初始化*/
        for (int i = 0; i < 100; i++) {
            Blog blog=new Blog();
            Date date=new Date();
            blog.setId((1000L+i)).setName(UUID.randomUUID().toString()).setCreateTime(date).setUpdateTime(date);
            list.add(blog);
        }
        long t1=System.currentTimeMillis();
        list.forEach(user -> batchSessionMapper.insert(user));
        batchSession.commit();
        long t2=System.currentTimeMillis();
        System.out.println("执行时间为"+(t2-t1)+"ms");    //1525ms
        batchSession.commit();
    }
}
