package transaction;

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.Application;
import com.Config.AppConfig1;
import com.Domain.Context;
import com.Domain.User;
import com.Mapper.UserMapper;
import com.Service.UserService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class MybatisTest {
	private static final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
			AppConfig1.class);
	@Autowired
	UserService userService;

	/**
	 * 自定义TypeHandler类
	 */
	@Test
	public void test() {
		List<User> user = userService.findUser();
		System.out.println(user);
	}

	/**
	 * Mybatis 批量插入数据库代码
	 */
	@Test
	public void insertOptimistic() {
		SqlSessionFactory sqlSessionFactory = context.getBean("sqlSessionFactory", SqlSessionFactory.class);
		// sqlSession 开启事务。 ExecutorType.REUSE 保证batch 事务的合理使用，
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,
				TransactionIsolationLevel.READ_COMMITTED);
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);

		for (int i = 1; i < 20; i++) {
			User user = new User();
			user.setId(String.valueOf(i));
			user.setUsername("user" + i);
			user.setPassword("123456");
			Context build = Context.builder().id(user.getId()).username(user.getUsername()).password(user.getPassword())
					.context("context").build();
			build.setContext("context:" + i);
			user.setContext(build);
			mapper.insert(user);
		}
		// 刷新
		sqlSession.flushStatements();
	}
    /**
     * 提供单对象，和多对象参数， sql打印功能 => 查询
     */
    @Test
    public void selectUser() {
        String name = "张三";
        User user = userService.selectUser(name);
        System.out.println(user);
    }
}
