package cn.reghao.tnb.sb.db.mybatis;

import cn.reghao.tnb.sb.multi.mybatis.mapper.UserMapper;
import cn.reghao.tnb.sb.multi.mybatis.model.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 java.io.IOException;
import java.io.InputStream;

/**
 * @author reghao
 * @date 2023-04-13 16:18:54
 */
public class MybatisDemo {
    static void select() throws IOException {
        String resource = "mybatis-config.xml";
        // 1.加载配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 2.创建SqlSessionFactory对象实际创建的是DefaultSqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 3.创建SqlSession对象实际创建的是DefaultSqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 4.创建代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 5.执行查询语句
        User user = mapper.findByName("abc");

        // 6.释放资源
        sqlSession.close();
        inputStream.close();
    }

    static void select1() {
        SqlSessionFactory sqlSessionFactory = MyBatisConfig.sqlSessionFactory();
        SqlSession session = sqlSessionFactory.openSession(true);
        UserMapper userMapper = session.getMapper(UserMapper.class);

        User user = userMapper.findByName("abc");
        session.close();
    }

    static void insert() {
        SqlSessionFactory sqlSessionFactory = MyBatisConfig.sqlSessionFactory();
        SqlSession session = sqlSessionFactory.openSession(true);
        UserMapper userMapper = session.getMapper(UserMapper.class);

        User user = userMapper.findByName("abc");
        /*for (int i = 0; i < 2; i++) {
            List<User> list = new ArrayList<>();
            for (int j = 0; j < 10_000; j++) {
                String name = RandomString.getString(8);
                list.add(new User(name, 30));
            }
            userMapper.saveAll(list);
            System.out.println(LocalDateTime.now() + " save 1w records");
        }*/

        /*session.commit();
        session.rollback();*/
        session.close();
    }

    public static void main(String[] args) throws IOException {
        //select();
        insert();
    }
}
