image.png

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



    image.png
    image.png