package com.cesgroup.mybatis;

import com.alibaba.fastjson.JSONObject;
import com.cesgroup.mybatis.entity.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 java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MybatisTest {
    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();
        }
    }

    @Test
    public void testSelectUser() {
        User user = sqlSession.selectOne("MyMapper.selectUser", 1);
        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void testInsertJsonObject() {
        JSONObject userInfObject = new JSONObject();
        userInfObject.put("address", "广东顺德");
        userInfObject.put("email", "ceshi@cesgroup.com.cn");
        Map userMap = new HashMap();
        userMap.put("id", 20);
        userMap.put("name", "测试");
        userMap.put("info", userInfObject);
        int num = sqlSession.insert("MyMapper.insert",userMap);
        sqlSession.commit();
        System.out.println("影响的行数:" + num);
    }
}
