CH10-整体流程
1. 通过 Resource 加载配置
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;
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
2. 实例化 sqlSessionFactoryBuilder 构造器
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3. 通过 build 中 XmlConfigBuilder 类解析文件流以及环境和属性
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
var5 = this.build(parser.parse());
4. 将配置信息存放到 Configuration 中
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
5. 实例化 SqlSessionFactory 实现类 DefaultSqlSessionFactory
6. 由 TransactionFactory 创建一个 Transaction 事务对象
7. 创建执行器 Excutor,执行 mapper
8. 创建 SqlSession 接口实现类 DefaultSqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession()
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
9. 执行 CRUD
10. 判断是否成功,失败则回滚到事务提交器
11. 提交事务
sqlSession.commit();
12. 关闭
sqlSession.close();
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.