//1.读取配置文件
//InputStream inputStream = MybatisTest.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
//3.使用工厂生产SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
UserDao mapper = sqlSession.getMapper(UserDao.class);
//5.使用代理对象执行方法
List<User> userList = mapper.findAll();
for(User user:userList){
System.out.println(user);
}
//6.释放资源
sqlSession.close();
inputStream.close();
1.读取配置文件
2.创建SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
使用了构建者模式,具有如下优点:
1)降低代码耦合度。在建造者模式中,客户端不需要知道产品内部是如何实现的,我们只需得到产品的对象。并且使用导演者和建造者分离组装过程和组件具体构造过程,具有灵活的扩展性。
2)优秀的扩展性。具体建造者相互独立,方便扩展,符合开闭原则。
3.使用工厂生产SqlSession对象
SqlSession sqlSession = factory.openSession();
工厂模式的优势:降低类之间的依赖关系;
4.使用SqlSession创建Dao接口的代理对象
UserDao mapper = sqlSession.getMapper(UserDao.class);
代理模式的优势:不修改源码的基础上对现有方法增强;