package test;

import java.io.InputStream;
import java.util.Date;

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.apache.tomcat.util.http.fileupload.IOUtils;
import org.json.JSONObject;

import entity.Test0Entity;
import mapper.Test0Mapper;

public class MyBatisTest0 {

    public static void main(String[] args) {

        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        SqlSession session = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            Test0Mapper mapper = session.getMapper(Test0Mapper.class);
            Date s = new Date();
            
            // 批量导入
            for (int i = 1; i <= 1000; i++) {
                JSONObject json = new JSONObject();
                json.put("name", "花花" + i);
                mapper.insertTest0Entity(i, json);
                if (i % 100 == 0) {
                    session.flushStatements();
                    session.commit();
                }
            }
            session.commit();
            Date e = new Date();
            
            System.out.println(e.getTime() - s.getTime());
            
            // 查询
            Test0Entity test0 = mapper.selectTest0Entity(1);
            System.out.println(test0.getId() + ": " + test0.getJson().getString("name"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(session);
        }
    }

}
