1.介绍和使用
Ø SqlSession:代表Java程序和数据库之间的会话。(HttpSession是Java程序和浏览器之间的会话)
Ø SqlSessionFactory:是“生产”SqlSession的“工厂”。
Ø 工厂模式:如果创建某一个对象,使用的过程基本固定,就可以把创建这个对象的相关代码封装到一个“工厂类”中,以后都使用这个工厂类来“生产”所需要的对象。
//1.获取核心配置文件的输入流
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3.获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//4.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//6.调用mapper接口中的方法,实现添加用户信息的功能
int result = mapper.insertUser();
//7.输出
System.out.println("结果"+result);
//8.提交事务
sqlSession.commit();
//9.关闭资源
sqlSession.close();
inputStream.close();
2.简化1
(省略步骤8)
//4.获取SqlSession对象(能自动提交)
SqlSession sqlSession = sqlSessionFactory.openSession(true);
3.简化2
(1)先创建SqlSessionUtil
public class SqlSessionUtil {
public static SqlSession getSqlSession(){
//1.获取核心配置文件的输入流
InputStream inputStream = null;
SqlSession sqlSession =null;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3.获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//4.获取SqlSession对象(能自动提交)
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
(2)Test
//1.获取SqlSession对象
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
//2.获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//3.调用mapper接口中的方法,实现添加用户信息的功能
int result = mapper.insertUser();
//4.输出
System.out.println("结果"+result);
//5.关闭资源
sqlSession.close();
标签:mapper,对象,SqlSession,对应,获取,sqlSession,测试,SqlSessionFactoryBuilder,junit
From: https://blog.csdn.net/2301_79659699/article/details/139205183