package com.itheima.pojo;
import com.itheima.mapper.UserMapper;
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.InputStream;
import java.util.List;
/**
* Mybatis 的代理开发
*/
public class MyBatisDemo2 {
public static void main(String[] args) throws Exception {
// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory (sql会话工厂)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3. 执行sql
// 由于里面的sql语句是查询所有字段 :select * from tb_user;, 所以要用selectList的API,查询一个就用selectone
// List<User> users = sqlSession.selectList("test.selectAll");// 参数是 空间名.标识名(id)
// 3.1 获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
// 打印查到的字段数据集合
System.out.println(users);
// 4.释放资源
sqlSession.close();
}
}