当前位置:网站首页>Sqlsessionfactory and sqlsession details
Sqlsessionfactory and sqlsession details
2022-06-10 11:23:00 【andQVQ】
List of articles
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 :
- 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
- By configuring objects , You can create a SqlSessionFactoryBuilder object
new SqlSessionFactoryBuilder().build(inputStream);// Building session factory classes
- adopt SqlSessionFactoryBuilder get SqlSessionFactory Example .
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSessionFactory The instance of can obtain the operation data SqlSession example , Operate the database through this example
SqlSession session = sqlSessionFactory.openSession();

SqlSessionFactory and SqlSession Specific implementation process
- 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;
}
- 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();
}
}
- 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());
}
}
边栏推荐
- Jeu plus durable casque sans fil réel, batterie super longue durée de vie, héros G1 en main
- Testing ovn manually based on LXD (by quqi99)
- How zoom closes the microphone when joining a meeting
- In commemoration of the 16th day of the first month, the total number of visits to the studio exceeded one million
- kubernetes常用命令-1-命令补全
- [communication protocol] UART, I2C, SPI review
- Android 13 针对 Intent Filters 安全的再升级
- 特权应用权限配置
- 深度剖析「圈组」关系系统设计 | 「圈组」技术系列文章
- Detailed explanation of redis
猜你喜欢

中国赛宝的面经

kubernetes常用命令-1-命令补全

How can the team be dissolved...
![[PaperNote] Confidential Computing Direction](/img/1e/0a41a6bb6fd752061c4608d3133eed.png)
[PaperNote] Confidential Computing Direction

87.(leaflet之家)leaflet军事标绘-直线箭头修改

数据在内存中的存储方式

数商云通讯行业数字化供应链协同系统:赋能通讯企业改善供应业务,增强市场竞争力

【网易云信】深度剖析「圈组」消息系统设计 | 「圈组」技术系列文章

纪念正月十六工作室总访问量突破百万

Practice of Flink CDC + Hudi massive data entering the lake in SF
随机推荐
软件测试基础
微信小程序注册流程详解
2021年中国电子元件营收第一,揭秘立讯精密高质量发展之路
High performance computing (2) -- a ten thousand foot tall building rises from the ground
特权应用权限配置
Is there any difference between exception and error
如何才能把团队给带解散。。。
[WIP] Openstack Masakari (by quqi99)
Android 13 针对 Intent Filters 安全的再升级
10款值得你去选择的AirPods Pro竞争产品
PID光离子化检测器用于电厂压缩空气含油量的在线监测
[signalr complete series] Implementation of signalr packet communication in net6
About one-way linked list
H.265编码原理入门
关于单向链表
Practice of Flink CDC in Dajian cloud warehouse
kubernetes 设置 Master 可调度与不可调度
Gan learning notes KL divergence, JS divergence, Wasserstein distance
source observable 发生错误之后会直接进入到catchError operator 而不是按照pipe里面的顺序处理之后再进入catchError
Practice of Flink CDC + Hudi massive data entering the lake in SF