package com.example.cuixiaowei;

import com.alibaba.fastjson.JSONObject;
import com.example.cuixiaowei.demo.User;
import org.apache.ibatis.io.Resources;
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.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CuixiaoweiApplicationTests {

    private SqlSession sqlSession=null;
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void configMybatis() {
        // 指定全局配置文件
        String resource = "mybatis-config.xml";
        // 读取配置文件
        InputStream inputStream;

        try {
            inputStream = Resources.getResourceAsStream(resource);

            // 构建sqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 获取sqlSession
            sqlSession= sqlSessionFactory.openSession(false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(sqlSession!=null) {
                //sqlSession.close();
            }
        }
    }

    /**
     *
     * 自定义解析器查询测试
     *
     * json串字段为  info
     */
    @Test
    public void testSelectUser() {
        User user = sqlSession.selectOne("MyMapper.selectUser", "31c6cb92-132d-4d6f-8ceb-24db6c3b6c29");
        System.out.println(user);
        sqlSession.close();
    }
    /**
     *
     * 自定义类型解析器插入测试
     */
    @Test
    public void testInsertJsonObject() {

        JSONObject userInfObject = new JSONObject();
        userInfObject.put("test", "测试");
        Map user = new HashMap();
        user.put("id", UUID.randomUUID().toString());
        user.put("name", "test");
        user.put("info", userInfObject);

        int a=sqlSession.insert("MyMapper.insert",user);
        sqlSession.commit();
        System.out.println("影响的行数:"+a);

    }
}
