MyBatis框架SqlSession浅析

news2024/12/27 3:30:59

1、SqlSessionFactory作用

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

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

2、SqlSessionFactoryBuilder

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

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

3、SqlSession

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

/**
 *    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
   */
  @Override
  void 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,实现基础功能。

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.coloradmin.cn/o/2144834.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++伟大发明--模版

C起初是不受外界关注的&#xff0c;别人觉得他和C语言没有本质上的区别&#xff0c;只是方便些&#xff0c;直到祖师爷发明了模版&#xff0c;开始和C语言有了根本的区别。 我们通过一个小小的例子来搞清楚什么是模版&#xff0c;模版的作用到底有多大&#xff0c;平时我们想要…

UAC2.0 麦克风——类特殊请求

UAC2.0 麦克风枚举过程参考 UAC2.0 麦克风——单声道 USB 麦克风(16bit) 文章目录 set interfaceget device status类特殊请求get curget rangevolume rangesample rangeset interface USB 请求代码 typedef enum {USB_REQ_GET_STATUS = 0 ,USB_REQ_CLEAR_FEATURE …

自动化中验证码的操作笔记,懂的赶紧收藏!

在自动化测试的过程中&#xff0c;验证码一直被视为一个“拦路虎”。很多测试人员在做接口或UI自动化时都会遇到验证码的阻碍&#xff0c;导致测试无法继续进行。今天&#xff0c;我们就来讨论如何在自动化过程中破解验证码&#xff0c;快速绕过这道关卡&#xff0c;轻松完成自…

【C51】独立按键控制LED灯

1.简介 在单片机应用系统中&#xff0c;常常使用轻触按键组成键盘。轻触按键具有自动回弹的特点&#xff0c;即按下按键&#xff0c;两个触点接通&#xff0c;放开按键&#xff0c;两个触点断开。轻触按键的外形及电路符号如图&#xff0c;通常轻触按键有4个引脚&#xff0c;4个…

Redis - 深入理解Redis事务

目录 Redis是如何实现事务的&#xff1f;事务中执行的命令出现错误&#xff0c;会回滚事务吗&#xff1f;同一个连接可以重复开启事务吗&#xff1f;多个客户端同时开启事务会怎样&#xff1f;使用Redis事务只用MULTI和EXEC吗&#xff1f;Redis中的WATCH机制是怎么实现的&#…

GAMES104:13 引擎工具链基础-学习笔记

文章目录 一&#xff0c;工具链二&#xff0c;复杂的工具2.1 界面GUI2.2 设计模式Design Pattern2.3 数据的加载和存储2.4 资产引用 三&#xff0c;资产加载Deserialization3.1 资产解析Parse3.2 资产版本兼容性&#xff08;Compatibility&#xff09; 四&#xff0c; 如何制作…

搞安全必看——IPS和IDS到底有啥区别?

号主&#xff1a;老杨丨11年资深网络工程师&#xff0c;更多网工提升干货&#xff0c;请关注公众号&#xff1a;网络工程师俱乐部 下午好&#xff0c;我的网工朋友。 随着数字化转型的加速推进&#xff0c;网络安全已成为各行业不可或缺的一环。对于现代企业和组织而言&#x…

【JavaEE初阶】多线程6(线程池\定时器)

欢迎关注个人主页&#xff1a;逸狼 创造不易&#xff0c;可以点点赞吗~ 如有错误&#xff0c;欢迎指出~ 目录 实例3:线程池 参数解释 核心线程数, 最大线程数 允许空闲的最大时间 ,时间单位 任务队列(阻塞队列) 线程工厂>工厂设计模式 拒绝策略 使用举例 模拟实现一个线…

从零开始讲DDR(0)——DDR的前世今生

一、计算机组成 计算机组成结构&#xff08;Computer Architecture&#xff09;是计算机系统的核心&#xff0c;它定义了计算机的基本工作原理和设计模式。计算机的组成可以分成以下3大类&#xff1a;中央处理器&#xff08;CPU&#xff09;、存储器和输入/输出子系统。 1.1 中…

Linux文件IO-基础知识了解及文件描述符

1、简介 本章给大家介绍 Linux 应用编程中最基础的知识&#xff0c;即文件 I/O&#xff08;Input、Outout&#xff09;&#xff0c;文件 I/O 指的是对文件的输入/输出操作&#xff0c;说白了就是对文件的读写操作&#xff1b;Linux 下一切皆文件&#xff0c;文件作为 Linux 系…

深度学习 之 常见损失函数简介:名称、作用及用法

引言 在机器学习和深度学习中&#xff0c;损失函数&#xff08;Loss Function&#xff09;是模型训练过程中一个不可或缺的部分。它用来度量模型预测结果与真实值之间的差异&#xff0c;从而指导模型参数的优化。合理选择损失函数对于提高模型的准确性和泛化能力至关重要。本文…

Mint Expedition Season 3 拉开帷幕:登顶高峰的时刻到了

自 7 月 15 日 Mint Expedition 启动以来&#xff0c;Mint&#xff0c;一条专注于 NFT 行业的以太坊 Layer 2&#xff0c;日常交易量和交易额都出现了爆发式增长。这一成功离不开 Mint 社区的合作&#xff0c;包括 Minters、Web3 去中心化应用程序的开发者&#xff0c;以及大量…

模电模块(一)

这个看起来功能挺全的&#xff0c;就是小贵&#xff0c;有时间自己做一个&#xff1a; 首页-康威科技-淘宝网 (taobao.com) 画一个集成板&#xff0c;集合上述模块的功能。

深圳国际VR/AR博览会圆满落下帷幕

近日&#xff0c;深圳国际VR/AR博览会在深圳国际会展中心2号馆圆满落下帷幕。该展会于9月11日至13日举行&#xff0c;是一个与光博会同期举行的大型盛会。 据主办方介绍&#xff0c;深圳国际VR/AR博览会&#xff08;Shenzhen International VR/AR Expo&#xff09;&#xff0c;…

力扣最热一百题——缺失的第一个正数

目录 题目链接&#xff1a;41. 缺失的第一个正数 - 力扣&#xff08;LeetCode&#xff09; 题目描述 示例 提示&#xff1a; 解法一&#xff1a;标记数组法 1. 将非正数和超出范围的数替换 2. 使用数组下标标记存在的数字 3. 找到第一个未标记的位置 4. 为什么时间复杂…

【与C++的邂逅】--- C++的IO流

Welcome to 9ilks Code World (๑•́ ₃ •̀๑) 个人主页: 9ilk (๑•́ ₃ •̀๑) 文章专栏&#xff1a; 与C的邂逅 本篇博客我们来了解C中io流的相关知识。 &#x1f3e0; C语言输入输出 C语言中我们用到的最频繁的输入输出方式就是scanf ()与printf()。 sc…

数据处理与统计分析篇-day03-Numpy环境搭建

概述 python优势 Python作为当下最为流行的编程语言之一 可以独立完成数据分析的各种任务 数据分析领域里有海量开源库 机器学习/深度学习领域最热门的编程语言 在爬虫&#xff0c;Web开发等领域均有应用 常用开源库 numpy NumPy(NumericalPython) 是 Python 语言的一…

创客中国AIGC专题赛冠军天鹜科技:AI蛋白质设计引领者

“落霞与孤鹜齐飞,秋水共长天一色——这句出自《滕王阁序》的诗句,是我作为江西人熟记于心的佳句。它描绘的天地壮丽景色常浮现于我的脑海,正是这种豁达与壮观,启发我们将公司命名为‘天鹜科技’,我们希望将源自自然的蛋白质与现代科技的创新精神相结合,打造蛋白质设计与应用的…

OpenBayes 教程上新 | AI 时代的「神笔马良」,Hyper-SD 一键启动教程上线!

每次脑海中的画面栩栩如生&#xff0c;想画下来却难以下笔&#xff1f; 每次画完自己觉得非常像&#xff0c;但是旁人却一头雾水&#xff1f; 每次想用文生图&#xff0c;但不知道如何精确地输入 prompt&#xff1f; AI 时代的「神笔马良」Hyper-SD 来了&#xff01; 仅需简…

基本仪表放大器+基本电容耦合隔离放大器+OTA(基本OTA电路+OTA增益)

2024-9-18&#xff0c;星期三&#xff0c;21:37&#xff0c;天气&#xff1a;多云&#xff0c;心情&#xff1a;晴。大家中秋节都过的怎么样啊&#xff0c;如果没过爽也没有关系&#xff0c;因为再上八天班就能迎来10.1长假啦&#xff01;&#xff01;&#xff01;&#xff01;…