工厂方法模式的应用之 MyBatis SqlSessionFactory

在 MyBatis 中,SqlSessionFactory 和 SqlSession 就是工厂方法模式的应用。SqlSessionFactory 是工厂接口,它定义了创建 SqlSession 的方法。

SqlSessionFactory:

package org.apache.ibatis.session;
import java.sql.Connection;
public interface SqlSessionFactory {
SqlSession openSession();
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();
}

SqlSession:

package org.apache.ibatis.session;
import java.io.Closeable;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.executor.BatchResult;
public interface SqlSession extends Closeable {
<T> T selectOne(String statement);
<T> T selectOne(String statement, Object parameter);
<E> List<E> selectList(String statement);
// ...
}

DefaultSqlSessionFactory 实现了 SqlSessionFactory 接口:

public class DefaultSqlSessionFactory implements SqlSessionFactory {
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
// ...
}

其实现方法的返回值是 DefaultSqlSession 对象,DefaultSqlSession 实现了 SqlSession 接口:

public class DefaultSqlSession implements SqlSession {
@Override
public <T> T selectOne(String statement) {
return this.<T>selectOne(statement, null);
}
// ...
}
posted @   Higurashi-kagome  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2023-03-06 Vue 项目配置文件中的 devServer
2022-03-06 创建《MySQL 必知必会》中的样例表
2022-03-06 MySQL 客户端和服务器
2022-03-06 数据库、DBMS、MySQL、SQL
点击右上角即可分享
微信分享提示