当前位置:网站首页>Sqlsessionfactory and sqlsession details

Sqlsessionfactory and sqlsession details

2022-06-10 11:23:00 andQVQ

SqlSessionFactory

1.SqlSessionFactory yes MyBatis The key object of , It is a compiled memory image of a single database mapping relationship .

2.SqlSessionFactory An instance of an object can be found by SqlSessionFactoryBuilder Object class gets , and SqlSessionFactoryBuilder You can from XML Configuration file or a pre-customized one Configuration SqlSessionFactory Example .

3. every last MyBatis All of the applications have a SqlSessionFactory An instance of an object is the core .

4.SqlSessionFactory It's thread safe ,SqlSessionFactory Once created , Should exist during application execution . Do not create multiple times while the application is running , The singleton mode is recommended .

5.SqlSessionFactory Is to create SqlSession Our factory .

SqlSessionFactory The interface source code is as follows :

package org.apache.ibatis.session; 

import java.sql.Connection; 

public interface SqlSessionFactory {
     
  SqlSession openSession();// This method is most often used , Used to create SqlSession object .
  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

1.SqlSession yes MyBatis The key object of , Is exclusive to performing persistent operations , Be similar to JDBC Medium Connection.

2. It is a single threaded object that performs interaction between the application and the persistence layer , It's also MyBatis The key object to perform the persistence operation .

3.SqlSession Object contains all the execution in the database context SQL How to operate , Its bottom layer encapsulates JDBC Connect , It can be used SqlSession Instance to directly execute the mapped SQL sentence .

4. Each thread should have its own SqlSession example .

5.SqlSession Instances of cannot be shared , meanwhile SqlSession Threads are also not safe , Never say SqlSeesion Instance references are placed in static fields or even instance fields of a class . We must not SqlSession Instance references are placed in any type of administrative scope , such as Servlet In the middle of HttpSession In the object .

6. Use up SqlSeesion Then close Session Very important , It should be ensured that finally Block to turn it off .

SqlSession The interface source code is as follows :

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.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); 
  <E> List<E> selectList(String statement, Object parameter); 
  <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); 
  <K, V> Map<K, V> selectMap(String statement, String mapKey); 
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); 
  <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); 
  void select(String statement, Object parameter, ResultHandler handler); 
  void select(String statement, ResultHandler handler); 
  void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler); 
  int insert(String statement); 
  int insert(String statement, Object parameter); 
  int update(String statement); 
  int update(String statement, Object parameter); 
  int delete(String statement); 
  int delete(String statement, Object parameter); 
  void commit(); void commit(boolean force); 
  void rollback(); 
  void rollback(boolean force); 
  List<BatchResult> flushStatements(); 
  void close(); 
  void clearCache(); 
  Configuration getConfiguration(); 
  <T> T getMapper(Class<T> type); 
  Connection getConnection(); 
}

SqlSessionFactory Call the process

mybatis The framework is mainly around SqlSessionFactory On going , The creation process is as follows :

  1. Define a Configuration object , It contains data sources 、 Business 、mapper File resources and attribute settings that affect database behavior settings
 String resource = "mybatis-config.xml";// Global profile path 
 InputStream inputStream = Resources.getResourceAsStream(resource);// Read xml file 
  1. By configuring objects , You can create a SqlSessionFactoryBuilder object
 new SqlSessionFactoryBuilder().build(inputStream);// Building session factory classes 
  1. adopt SqlSessionFactoryBuilder get SqlSessionFactory Example .
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  1. SqlSessionFactory The instance of can obtain the operation data SqlSession example , Operate the database through this example
SqlSession session = sqlSessionFactory.openSession();

 Insert picture description here

SqlSessionFactory and SqlSession Specific implementation process

  1. SqlSessionFactoryBuilder Read out mybatis Configuration file for , then build One DefaultSqlSessionFactory, Or get SqlSessionFactory
// The packages and specific methods involved in the source code are :
// The packages involved are :package org.apache.ibatis.session;

// The first class is :SqlSessionFactoryBuilder, The method of designing this class is the following :
public SqlSessionFactory build(InputStream inputStream) {
    
    return build(inputStream, null, null);
  }

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    
    try {
    
      // adopt XMLConfigBuilder Parse configuration file , The parsed configuration related information is encapsulated as a Configuration object 
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      // And then return a DefaultSqlSessionFactory
      return build(parser.parse());
    } catch (Exception e) {
    
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
    
      ErrorContext.instance().reset();
      try {
    
        inputStream.close();
      } catch (IOException e) {
    
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

 // obtain DefaultSqlSessionFactory
 public SqlSessionFactory build(Configuration config) {
    
   return new DefaultSqlSessionFactory(config);
 }

// The second class is :DefaultSqlSessionFactory, The methods involved are :
  public DefaultSqlSessionFactory(Configuration configuration) {
    
    this.configuration = configuration;
  }

  1. Get SqlSessionFactory after , You can use it SqlSessionFactory Methodical openSession To get SqlSession Object .
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    
  Transaction tx = null;
  try {
    
    // adopt Confuguration Object to get Mybatis Related configuration information , Environment Contains the data source of the transaction 
    // execType Is the actuator type , Defined in the configuration file 
    // SimpleExecutor -- SIMPLE  It's a common actuator .
    //ReuseExecutor - The executor reuses the preprocessing statement (prepared statements)
    //BatchExecutor -- It is a batch actuator 
    final Environment environment = configuration.getEnvironment();
    final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    // Define actuators , It's right statement Encapsulation 
    final Executor executor = configuration.newExecutor(tx, execType);
    // The last one to return SqlSession
    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();
  }
}
  1. obtain SqlSession Object can then be used SqlSession Internal methods CRUD Operation .

Be careful. ,Connection Object is in SqlSession After the object is created CURD Created in operation . After a deep search, find in ManagedTransaction Class Connection The key code of the object is as follows :

  protected void openConnection() throws SQLException {
    
    if (log.isDebugEnabled()) {
    
      log.debug("Opening JDBC Connection");
    }
    //dataSource  There are three sources ,JndiDatasource,PooledDataSource,UnpooledDataSource, Defined in the configuration file 
    this.connection = this.dataSource.getConnection();
    if (this.level != null) {
    
      this.connection.setTransactionIsolation(this.level.getLevel());
    }
  }

Reference resources 1

原网站

版权声明
本文为[andQVQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101102560098.html