package com.ces.mybatis;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import com.ces.mybatis.dao.IUserDao;
import com.ces.mybatis.model.Context;
import com.ces.mybatis.model.User;
import com.ces.mybatis.service.IUserService;

/**
 * Unit test for simple App.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class AppTest 
{
	private static final AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext("application.yml");
	
	// 注入“Converter”bean
    @Autowired
    private IUserService userService;

    /**
     * 1. 自定义TypeHandler类
     */
    @Test
    public void testa(){
    	List<User> user = userService.getAll();
        System.out.println(user);
    }
    
    /**
     * 2. Mybatis 批量插入数据库代码
     */
    @Test
    public void testb(){
    	SqlSessionFactory sqlSessionFactory = context
                .getBean("sqlSessionFactory", SqlSessionFactory.class);
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, TransactionIsolationLevel.READ_COMMITTED);
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        
    	List<User> users = new ArrayList<User>();
    	for(int i=0;i<3;i++){
    		User user = new User();
    		user.setUserId(String.valueOf(i));
    		user.setUserName("admin"+i);
    		user.setPassword("123");
    		Context context = new Context();
    		context.setCity("city");
    		context.setProvince("province");
    		context.setDistrict("district");
    		user.setContext(context);
    		users.add(user);
    	}
    	boolean isSuccess = mapper.insertOrUpdateByBatch(users);
        System.out.println(isSuccess);
        // 刷新
        sqlSession.flushStatements();
    }
}
