MyBatis框架SqlSession浅析

devtools/2024/9/23 6:11:56/

1、SqlSessionFactory作用

MyBatis框架SqlSessionFactory是线程安全的,负责创建SqlSession

       DefaultSqlSessionFactory是线程安全的,属性Final。

2、SqlSessionFactoryBuilder

SqlSessionFactoryBuilder负责创建SqlSessionFactory。SqlSessionFactoryBuilder则可以从XML配置文件或一个预先定制的Configuration的实例构建出SqlSessionFactory的实例。

java">  public SqlSessionFactory build(Configuration config) {return new DefaultSqlSessionFactory(config);}

3、SqlSession

作用:封装数据库操作,线程不安全。

java">/***    Copyright 2009-2016 the original author or authors.**    Licensed under the Apache License, Version 2.0 (the "License");*    you may not use this file except in compliance with the License.*    You may obtain a copy of the License at**       http://www.apache.org/licenses/LICENSE-2.0**    Unless required by applicable law or agreed to in writing, software*    distributed under the License is distributed on an "AS IS" BASIS,*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*    See the License for the specific language governing permissions and*    limitations under the License.*/
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;/*** The primary Java interface for working with MyBatis.* Through this interface you can execute commands, get mappers and manage transactions.** @author Clinton Begin*/
public interface SqlSession extends Closeable {/*** Retrieve a single row mapped from the statement key* @param <T> the returned object type* @param statement* @return Mapped object*/<T> T selectOne(String statement);/*** Retrieve a single row mapped from the statement key and parameter.* @param <T> the returned object type* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @return Mapped object*/<T> T selectOne(String statement, Object parameter);/*** Retrieve a list of mapped objects from the statement key and parameter.* @param <E> the returned list element type* @param statement Unique identifier matching the statement to use.* @return List of mapped object*/<E> List<E> selectList(String statement);/*** Retrieve a list of mapped objects from the statement key and parameter.* @param <E> the returned list element type* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @return List of mapped object*/<E> List<E> selectList(String statement, Object parameter);/*** Retrieve a list of mapped objects from the statement key and parameter,* within the specified row bounds.* @param <E> the returned list element type* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @param rowBounds  Bounds to limit object retrieval* @return List of mapped object*/<E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds);/*** The selectMap is a special case in that it is designed to convert a list* of results into a Map based on one of the properties in the resulting* objects.* Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id")* @param <K> the returned Map keys type* @param <V> the returned Map values type* @param statement Unique identifier matching the statement to use.* @param mapKey The property to use as key for each value in the list.* @return Map containing key pair data.*/<K, V> Map<K, V> selectMap(String statement, String mapKey);/*** The selectMap is a special case in that it is designed to convert a list* of results into a Map based on one of the properties in the resulting* objects.* @param <K> the returned Map keys type* @param <V> the returned Map values type* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @param mapKey The property to use as key for each value in the list.* @return Map containing key pair data.*/<K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);/*** The selectMap is a special case in that it is designed to convert a list* of results into a Map based on one of the properties in the resulting* objects.* @param <K> the returned Map keys type* @param <V> the returned Map values type* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @param mapKey The property to use as key for each value in the list.* @param rowBounds  Bounds to limit object retrieval* @return Map containing key pair data.*/<K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds);/*** A Cursor offers the same results as a List, except it fetches data lazily using an Iterator.* @param <T> the returned cursor element type.* @param statement Unique identifier matching the statement to use.* @return Cursor of mapped objects*/<T> Cursor<T> selectCursor(String statement);/*** A Cursor offers the same results as a List, except it fetches data lazily using an Iterator.* @param <T> the returned cursor element type.* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @return Cursor of mapped objects*/<T> Cursor<T> selectCursor(String statement, Object parameter);/*** A Cursor offers the same results as a List, except it fetches data lazily using an Iterator.* @param <T> the returned cursor element type.* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @param rowBounds  Bounds to limit object retrieval* @return Cursor of mapped objects*/<T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);/*** Retrieve a single row mapped from the statement key and parameter* using a {@code ResultHandler}.* @param statement Unique identifier matching the statement to use.* @param parameter A parameter object to pass to the statement.* @param handler ResultHandler that will handle each retrieved row*/void select(String statement, Object parameter, ResultHandler handler);/*** Retrieve a single row mapped from the statement* using a {@code ResultHandler}.* @param statement Unique identifier matching the statement to use.* @param handler ResultHandler that will handle each retrieved row*/void select(String statement, ResultHandler handler);/*** Retrieve a single row mapped from the statement key and parameter* using a {@code ResultHandler} and {@code RowBounds}* @param statement Unique identifier matching the statement to use.* @param rowBounds RowBound instance to limit the query results* @param handler ResultHandler that will handle each retrieved row*/void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);/*** Execute an insert statement.* @param statement Unique identifier matching the statement to execute.* @return int The number of rows affected by the insert.*/int insert(String statement);/*** Execute an insert statement with the given parameter object. Any generated* autoincrement values or selectKey entries will modify the given parameter* object properties. Only the number of rows affected will be returned.* @param statement Unique identifier matching the statement to execute.* @param parameter A parameter object to pass to the statement.* @return int The number of rows affected by the insert.*/int insert(String statement, Object parameter);/*** Execute an update statement. The number of rows affected will be returned.* @param statement Unique identifier matching the statement to execute.* @return int The number of rows affected by the update.*/int update(String statement);/*** Execute an update statement. The number of rows affected will be returned.* @param statement Unique identifier matching the statement to execute.* @param parameter A parameter object to pass to the statement.* @return int The number of rows affected by the update.*/int update(String statement, Object parameter);/*** Execute a delete statement. The number of rows affected will be returned.* @param statement Unique identifier matching the statement to execute.* @return int The number of rows affected by the delete.*/int delete(String statement);/*** Execute a delete statement. The number of rows affected will be returned.* @param statement Unique identifier matching the statement to execute.* @param parameter A parameter object to pass to the statement.* @return int The number of rows affected by the delete.*/int delete(String statement, Object parameter);/*** Flushes batch statements and commits database connection.* Note that database connection will not be committed if no updates/deletes/inserts were called.* To force the commit call {@link SqlSession#commit(boolean)}*/void commit();/*** Flushes batch statements and commits database connection.* @param force forces connection commit*/void commit(boolean force);/*** Discards pending batch statements and rolls database connection back.* Note that database connection will not be rolled back if no updates/deletes/inserts were called.* To force the rollback call {@link SqlSession#rollback(boolean)}*/void rollback();/*** Discards pending batch statements and rolls database connection back.* Note that database connection will not be rolled back if no updates/deletes/inserts were called.* @param force forces connection rollback*/void rollback(boolean force);/*** Flushes batch statements.* @return BatchResult list of updated records* @since 3.0.6*/List<BatchResult> flushStatements();/*** Closes the session*/@Overridevoid close();/*** Clears local session cache*/void clearCache();/*** Retrieves current configuration* @return Configuration*/Configuration getConfiguration();/*** Retrieves a mapper.* @param <T> the mapper type* @param type Mapper interface class* @return a mapper bound to this SqlSession*/<T> T getMapper(Class<T> type);/*** Retrieves inner database connection* @return Connection*/Connection getConnection();
}
DefaultSqlSession:SqlSession的默认实现,不是线程安全的.

线程安全性考虑,在使用MyBatis时,通过mapper接口的使用是基于动态代理的,提供了两种情况下的线程安全性:

在不使用事务的情况下,每个SQL操作会新建一个SqlSession对象,这种方式是线程安全的。

在使用事务时,通过ThreadLocal保证每个线程对应一个SqlSession对象,因此也是线程安全的‌。

4、SqlSessionManager

实现SqlSession和SqlSessionFactory,实现基础功能。

java">public class SqlSessionManager implements SqlSessionFactory, SqlSession {private final SqlSessionFactory sqlSessionFactory;private final SqlSession sqlSessionProxy;private final ThreadLocal<SqlSession> localSqlSession = new ThreadLocal<>();private SqlSessionManager(SqlSessionFactory sqlSessionFactory) {this.sqlSessionFactory = sqlSessionFactory;this.sqlSessionProxy = (SqlSession) Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(),new Class[]{SqlSession.class},new SqlSessionInterceptor());}

5、SqlSessionTemplate

是一个线程安全的类,它实现了SqlSession接口。通过SqlSessionTemplate可以完成对数据库的CRUD操作,并且保证单例线程安全。是位于mybatis-spring 2.0.0包中,通过SqlSessionTemplate可以完成对数据库的CRUD操作,并且保证单例线程安全。SqlSessionTemplate通过拥有一个SqlSessionProxy的代理对象来实现这一点,这个代理对象在调用时会导向SqlSessionInterceptor的invoke方法触发代理逻辑,从而保证线程安全。

6、三种Executor执行器

  • BaseExecutor

  • SimpleExecutor

SimpleExecutor 每执行一次update或select,就开启一个Statement对象,用完立刻关闭Statement对象。

  • PauseExecutor。

PauseExecutor 执行update或select,以sql做为key查找Statement对象,存在就使用,不存在就创建,用完后,不关闭Statement对象,而且放置于Map内,供下一次使用。简言之,就是重复使用Statement对象。

  • BatchExecutor 

BatchExecutor 执行update,将所有sql通过addBatch()都添加到批处理中,等待统一执行executeBatch(),它缓存了多个Statement对象,每个Statement对象都是addBatch()完毕后,等待逐一执行executeBatch()批处理。与JDBC批处理相同。


http://www.ppmy.cn/devtools/115852.html

相关文章

【网络安全】依赖混淆漏洞实现RCE

未经许可&#xff0c;不得转载。 文章目录 正文 依赖混淆是一种供应链攻击漏洞&#xff0c;发生在企业的内部依赖包错误地从公共库&#xff08;如npm&#xff09;下载&#xff0c;而不是从其私有注册表下载。攻击者可以在公共注册表中上传一个与公司内部包同名的恶意包&#xf…

【machine learning-15-如何判定梯度下降是否在收敛】

我们在运行梯度下降的时候&#xff0c;如何判定梯度下降是否在收敛呢&#xff1f; 梯度下降的时候&#xff0c;权重和偏置根据如下的公式同时更新&#xff1a; 程序要做的就是更新w 和 b&#xff0c;让梯度下降尽快的收敛&#xff0c;但是如何判定正在收敛呢&#xff1f; 方法…

Go小专栏 第一期

Go的前世今生 如标题所述&#xff0c;这篇文章主要是来聊聊Go的历史&#xff0c;现状以及未来&#xff0c;或者也可称为Go的发展脉络。我认为任何事物存在皆有原因&#xff0c;技术也不例外。这篇文章主要探讨Go为什么会出现&#xff0c;Go的特点。 Go为什么会出现&#xff1…

Android-UI设计

控件 控件是用户与应用交互的元素。常见的控件包括&#xff1a; 按钮 (Button)&#xff1a;用于执行动作。文本框 (EditText)&#xff1a;让用户输入文本。复选框 (CheckBox)&#xff1a;允许用户选择或取消选择某个选项。单选按钮 (RadioButton)&#xff1a;用于在多个选项中…

Maven国内镜像(四种)

配置Maven使用国内镜像是一个常见的做法&#xff0c;因为这样可以显著提高依赖下载的速度并避免网络不稳定带来的问题 在 settings.xml 文件中&#xff0c;需要添加或修改 <mirrors> 标签来指定国内镜像。 以下是几个可用的镜像 1. 阿里云 <mirrors> <mi…

prompt攻击与防范

Prompt攻击是指通过精心设计的输入提示来操纵AI模型&#xff0c;使其产生不准确或有害的输出。这些攻击可能包括提示词注入、提示词泄露和提示词越狱等。攻击者可能会尝试通过提供包含恶意内容的输入&#xff0c;来操纵语言模型的输出&#xff0c;或者从模型的响应中提取敏感或…

美食共享圈:Spring Boot校园周边美食平台

第二章 系统分析 2.1 可行性分析 可行性分析的目的是确定一个系统是否有必要开发、确定系统是否能以最小的代价实现。其工作主要有三个方面&#xff0c;分别是技术、经济和社会三方面的可行性。我会从这三个方面对网上校园周边美食探索及分享平台进行详细的分析。 2.1.1技术可行…

html 几行的空间分成3个区域

1.代码 <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name"viewport" content"widthdevice-width, initial-scale1.0"> <title>三个区域示例</title> …