import com.ces.ObjectMapperUtils;
import com.ces.mapper.UserMapper;
import com.ces.pojo.Dept;
import com.ces.pojo.User;
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 {
    UserMapper userMapper;
    SqlSession sqlSession;
    SqlSessionFactory sqlSessionFactory;
    @Before
    public void init() throws IOException {
        sqlSessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis/mybatis-config.xml"));
        sqlSession = sqlSessionFactory.openSession();
        userMapper=sqlSession.getMapper(UserMapper.class);
    }

    /**2.批量执行插入数据*/
    @Test
    public void testBatch(){
        SqlSession batchSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        UserMapper batchSessionMapper = batchSession.getMapper(UserMapper.class);
        List<User> list=new ArrayList<>(100);
        /**初始化*/
        for (int i = 0; i < 100; i++) {
            User user=new User().setName(UUID.randomUUID().toString())
                    .setCreateTime(new Date()).setAge(new Random().nextInt(20))
                    .setDept(new Dept().setName(UUID.randomUUID().toString())
                            .setId(i))
                    .setSalary(new Random().nextDouble())
                    .setId(i);
            user.setUpdateTime(user.getCreateTime());
            list.add(user);
        }
        long t1=System.currentTimeMillis();
        list.forEach(user -> batchSessionMapper.insert(user));
        batchSession.commit();
        long t2=System.currentTimeMillis();
        System.out.println("执行时间为"+(t2-t1)+"ms");    //1525ms
    }

    /**1.自定义typeHandler类完成数据库字段context，定义varchar，内容是json，直接和java'对象映射
     * @see com.ces.config.UserHandler
     * */
    @Test
    @Ignore
    public void test(){
        /**插入*/
        Dept dept=new Dept().setId(1).setName("大数据一部");
        User user=new User().setAge(20).setDept(dept).setId(1).setSalary(3000.0)
                .setName("Tom").setCreateTime(new Date());
        user.setUpdateTime(user.getCreateTime());
        long t1=System.currentTimeMillis();
        int i = userMapper.insert(user);
        sqlSession.commit();
        long t2=System.currentTimeMillis();
        System.out.println("数据插入");
        System.out.println("影响了"+i+"行");
        System.out.println("执行时间为"+(t2-t1)+"ms");
        System.out.println("-----------------");
        /**查询*/
        long t3=System.currentTimeMillis();
        User one = userMapper.selectOne(7);
        long t4=System.currentTimeMillis();
        System.out.println("结果为："+one);
        System.out.println("执行时间为"+(t4-t3)+"ms");

    }
}
