MyBatis 如何创建 SqlSession 对象的?

MyBatis 创建 SqlSession 对象的过程主要由 SqlSessionFactory 接口及其实现类来完成。以下是详细步骤:

1. SqlSessionFactory 接口:

  • SqlSessionFactory 是 MyBatis 的核心接口之一,它负责创建 SqlSession 对象。 你可以将 SqlSessionFactory 视为 SqlSession 的工厂。
  • SqlSessionFactory 接口定义了多个 openSession() 方法,用于创建 SqlSession。这些方法提供了不同的选项,例如:
    * openSession(): 使用默认配置(通常是不自动提交事务)。
    * openSession(boolean autoCommit): 指定是否自动提交事务。
    * openSession(ExecutorType execType): 指定执行器类型 (SIMPLE, REUSE, BATCH)。
    * openSession(TransactionIsolationLevel level): 指定事务隔离级别。
    * openSession(Connection connection): 使用外部提供的数据库连接。

2. SqlSessionFactoryBuilder:

  • SqlSessionFactoryBuilder 是一个构建器类,用于构建 SqlSessionFactory 实例。
  • 它提供了多个 build() 方法,可以通过以下方式构建 SqlSessionFactory
    * 从 XML 配置文件 (mybatis-config.xml) 构建。
    * 从 Configuration 对象构建。
    * 从 InputStreamReader 构建。
// 从 XML 配置文件构建 SqlSessionFactory (最常见的方式)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 从 Configuration 对象构建 SqlSessionFactory
Configuration configuration = new Configuration();
// ... 添加配置信息 ...
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  • SqlSessionFactoryBuilder 在构建完 SqlSessionFactory 后,其自身的使命就完成了,通常不需要保留它的实例。最佳实践是在方法内部创建 SqlSessionFactoryBuilder,构建 SqlSessionFactory,然后丢弃 SqlSessionFactoryBuilder

3. DefaultSqlSessionFactory (默认实现):

  • DefaultSqlSessionFactorySqlSessionFactory 接口的默认实现类。
  • SqlSessionFactoryBuilderbuild() 方法通常会创建一个 DefaultSqlSessionFactory 实例。

4. openSession() 方法 (创建 SqlSession 的核心):

  • DefaultSqlSessionFactoryopenSession() 方法(及其重载方法)负责创建 SqlSession 对象。
  • 创建 SqlSession 的过程大致如下:
  1. 获取 Environment:Configuration 对象中获取 Environment 对象,Environment 对象包含了数据源、事务管理器等信息
  2. 创建 Transaction: 根据 Environment 中的 TransactionFactory 创建 Transaction 对象。Transaction 对象负责管理数据库事务。
  3. 创建 Executor: 根据配置信息(例如,defaultExecutorType 设置)和 Transaction 对象创建 Executor 对象。Executor 负责执行 SQL 语句,并处理缓存。
  4. 创建 DefaultSqlSession: 创建 DefaultSqlSession 对象,并将 ConfigurationExecutorautoCommit 标志(是否自动提交事务)传递给 DefaultSqlSession 的构造函数。
  5. 返回 DefaultSqlSession: openSession() 方法返回新创建的 DefaultSqlSession 对象。
    // DefaultSqlSessionFactory 的 openSessionFromDataSource() 方法 (简化版)
    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();
        }
    }
    

5. DefaultSqlSession:

  • DefaultSqlSessionSqlSession 接口的默认实现类。
  • 它包含了执行 SQL 语句、获取 Mapper 接口实例、管理事务等方法。
  • DefaultSqlSession 内部持有 Configuration 对象、Executor 对象和 autoCommit 标志。

总结:

MyBatis 创建 SqlSession 对象的过程如下:

  1. SqlSessionFactoryBuilder 构建 SqlSessionFactory (通常是 DefaultSqlSessionFactory)。
  2. 调用 SqlSessionFactoryopenSession() 方法。
  3. DefaultSqlSessionFactory 创建 TransactionExecutorDefaultSqlSession 对象。
  4. openSession() 方法返回 DefaultSqlSession 对象。

SqlSessionFactorySqlSession 的工厂,DefaultSqlSessionFactorySqlSessionFactory 的默认实现,DefaultSqlSessionSqlSession 的默认实现。SqlSessionFactoryBuilder 用于构建 SqlSessionFactory

### 回答1: Mybatis获取SqlSession对象的方法有两种: 1. 通过SqlSessionFactory获取SqlSession对象 首先需要创建一个SqlSessionFactory对象,可以通过读取mybatis的配置文件来创建,然后通过SqlSessionFactory对象的openSession()方法获取SqlSession对象。 示例代码: //读取mybatis配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); 2. 通过Spring框架获取SqlSession对象 如果项目中使用了Spring框架,可以通过Spring的容器来获取SqlSession对象。需要在Spring的配置文件中配置SqlSessionFactorySqlSessionTemplate两个Bean,然后通过@Autowired注解来注入SqlSessionTemplate对象。 示例代码: <!-- 配置SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 配置SqlSessionTemplate --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"/> </bean> //注入SqlSessionTemplate对象 @Autowired private SqlSessionTemplate sqlSessionTemplate; ### 回答2: MyBatis获取SqlSession对象是非常重要的,SqlSessionMyBatis操作数据库的核心对象,用来执行SQL语句、提交事务、获取映射器等。 三种获取SqlSession对象的方式: 1.使用SqlSessionFactoryBuilder来读取配置文件,创建SqlSessionFactory对象,再通过SqlSessionFactory对象创建SqlSession对象: ``` String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); ``` 2.使用MyBatis提供的Resources类,直接获取配置文件流,创建SqlSessionFactory对象,再通过SqlSessionFactory对象创建SqlSession对象: ``` String resource = "mybatis-config.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); ``` 3.使用Spring框架集成MyBatis,通过SqlSessionFactoryBean配置SqlSessionFactory,再通过SqlSessionFactory创建SqlSession对象: ``` <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"/> </bean> ``` 无论是哪种方式获取SqlSession对象,都要注意调用close方法将SqlSession对象关闭,释放数据库资源。 否则,容易出现数据库连接泄漏的问题,影响系统性能。因此,在使用MyBatis操作数据库时,一定要注意SqlSession的使用和关闭。 ### 回答3: Mybatis是一个基于Java的开源数据访问框架,提供了面向对象的持久化操作方式,是许多Java Web应用的首选框架。其核心是SqlSessionMybatis通过SqlSession与数据库进行交互。因此,获取SqlSession对象是使用Mybatis的第一步。 获取SqlSession对象主要有以下两种方式: 1. SqlSessionFactoryBuilder 首先,需要创建SqlSessionFactoryBuilder对象,通过它配置Mybatis创建SqlSessionFactory对象,再通过SqlSessionFactory对象生成SqlSession对象。示例代码如下: ``` InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = builder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); ``` 这里,首先使用Resources.getResourceAsStream加载Mybatis配置文件mybatis-config.xml,然后创建SqlSessionFactoryBuilder对象builder,调用其build方法创建SqlSessionFactory对象sqlSessionFactory,最后通过SqlSessionFactory对象的openSession方法获取SqlSession对象sqlSession。 2. @Inject注解 另外一种获取SqlSession对象的方式是使用@Inject注解。通过在Mapper接口的字段或setter方法上添加@Inject注解,Mybatis会自动注入SqlSession对象。示例代码如下: ``` public interface UserMapper { @Inject SqlSession sqlSession; // 或者 void setSqlSession(SqlSession sqlSession); } ``` 这里,通过@Inject注解,Mybatis会自动注入SqlSession对象sqlSession。另外也可以通过setter方法进行注入。 总结起来,获取SqlSession对象有两种常用方式:通过SqlSessionFactoryBuilder对象创建,或在Mapper接口中使用@Inject注解。根据实际情况选择合适的方式进行使用即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰糖心书房

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值