# Mybatis commonly used objects SqlSessionFactory, SqlSession to understand and learn

Mybatis commonly used objects SqlSessionFactory, SqlSession to understand and learn

Mybatis dependency package
<dependency>
	<groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
</dependency>
Mybatis automatic assembly steps
  • Load configuration file
  • Get the SqlSessionFactory object
  • Get SqlSessionFactoryBuilder and configuration file stream to get SqlSessionFactory object
  • Use the SqlSessionFactory object to open a SqlSession
  • Obtain the corresponding Mapper object through SqlSession
  • Call the corresponding interface through the Mapper object to query the database

SqlSessionFactory

  • SqlSessionFactory: Factory design pattern, a factory to create SqlSession. The application of Mybatis is based on an instance of SqlSessionFactory. SqlSessionFactoryBuilder can build instances from XML configuration files or use Configuration, and SqlSessionFactory creation methods.
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  • build()
public SqlSessionFactory build(Configuration config) {
    
    
    return new DefaultSqlSessionFactory(config);
}
public DefaultSqlSessionFactory(Configuration configuration) {
    
    
    this.configuration = configuration;
}
SqlSessionFactory creation steps
  • Define a Configuration object, which contains data sources, transactions, mapper file resources, etc.
  • Create a SqlSessionFactoryBuilder object through the configuration object.
  • Obtain an instance of SqlSessionFactory through SqlSessionFactoryBuilder.
  • The instance of SqlSessionFactory can obtain the instance of SqlSession that operates the database, and operate the database through this instance.
Code example
  • configuration.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="ssm/jdbc.properties"></properties>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}"/>
				<property name="url" value="${jdbc.url}"/>
				<property name="username" value="${jdbc.username}"/>
				<property name="password" value="${jdbc.password}"/>
			</dataSource>
		</environment>
	</environments>	
	
	<mappers>
		<mapper resource="ssm/BlogMapper.xml"/>
	</mappers>
</configuration>
  • Read xml configuration demo
public class GetSqlSessionFactoryFromXML {
    
    
 
	public static void main(String[] args) throws IOException {
    
    
		//配置文件的名称
		String resource = "ssm/configuration.xml";
		//通过Mybatis包中的Resources对象很轻松的获取到配置文件
		Reader reader = Resources.getResourceAsReader(resource);
		//通过SqlSessionFactoryBuilder创建
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		//获得session实例
		SqlSession session =sqlSessionFactory.openSession();
		User user = new User();
		user.setId(8);
		//完成数据库的插入
		session.insert("add", user);
		session.commit();
		session.close();
		System.out.println(sqlSessionFactory);
	}
}
  • java code configuration
@Bean
public SqlSessionFactory sqlSessionFactory(){
    
    
    try {
    
    
        // 数据源连接信息
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("test");
        dataSource.setUsername("test");
        dataSource.setPassword("test");

        // 采用Mybatis的JDBC事务方式
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("myenverniement", transactionFactory, dataSource);
        // 创建Configuration对象
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(MetaDataTagMapper.class);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        logger.info("===========================SqlSessionFactory配置完成");
        return sqlSessionFactory;
    }catch (Exception e){
    
    
        logger.error("===========================SqlSessionFactory配置失败"+e.getMessage(),e);
        return null;
    }
}
@Bean
public SqlSession sqlSession(SqlSessionFactory sqlSessionFactory){
    
    
    try{
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Object> objects = sqlSession.selectList("select 1");
        return sqlSession;
    }catch (Exception e){
    
    
        logger.info(e.getMessage());
        return null;
    }
}

SqlSession

SqlSession creation steps:
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();
    }
}
  • Get Environment from the configuration;
  • Get DataSource from Environment;
  • Obtain TransactionFactory from Environment;
  • Get the database connection object Connection from the DataSource;
  • Create a transaction object Transaction on the obtained database;
  • Create an Executor object;
  • Create a SqlSession object;
DefaultSqlSession实现SqlSession
// statement Mapper接口的名称
// parameter sql参数
// rowsBounds 分页参数
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    
    
    try {
    
    
        // ms对应Xml中的一个语句,如select、insert等
        MappedStatement ms = configuration.getMappedStatement(statement);
        // 调用Executor处理Sql
        return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
    
    
        throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
    
    
        ErrorContext.instance().reset();
    }
}
Executor interface

All Mapper statements in Mybatis are executed through Executor. Executor is bound with SqlSession, each SqlSession has a new Executor object, created by Configuration.

  • SimpleExecutor: Directly execute according to the corresponding Sql, without additional operations.

  • BatchExecutor: batch update operation.

  • ReuseExcutor: Reusable executor. The object of reuse is Statement. The executor caches the same Sql Statement, eliminating the need to re-create the Statement.

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/109861871