设计模式总结
工厂模式
public interface SqlSessionFactory {
// 创建openSession无参,关键参数默认
SqlSession openSession();
// 创建是否自动提交的SqlSession,参数属于Connection的重要属性,以下方法类似
// 关键属性由创建者决定
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
Configuration getConfiguration();
}
构造器模式
使用心得:SqlSessionFactory实现类的构造方法public DefaultSqlSessionFactory(Configuration configuration),目前已有的资源(xml文件)需要转换,那么直接使用构造器,拿到xml,然后再build中进行转换来构造SqlSessionFactory
// 通过额外的参数转换成SqlSessionFactory真正需要的参数
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
// 最终是拿到Config创建SqlSessionFactory,使得SqlSessionFactory代码内的构造器更加简洁
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}