Mybatis工作原理?

南京工业大学高性能计算平台基础使用指南 高性能计算平台基础使用指南前言什么高性能计算南京工业大学高性能计算平台如何登录如何进行文件传输进行任务提交(本文以提交MATLAB任务为例)环境变量的配置(推荐)使用Environment Modules进行环境变量管理Modules 指令自定义MODULEFILE常见软件任务脚本 前言 第一次接触使用学校的高性能平台是在今年上半年进行毕业设计的时候,当时有大量的数据需要在Matab中进行模型运算,便向学校申请了账号,使用了HPC平台。计算速度确实比个人电脑快了太多太多。 近期,有很多初次想使用高性能计算 阅读详情

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!

if (obj instanceof Date) {

preparedStatement.setDate(i, (java.sql.Date) obj);

}

}

}

  • 单个参数比较简单直接设置值即可,Long、Integer、String …

  • 如果是一个类对象,需要通过获取 Field 属性,与参数 Map 进行匹配设置

  • 设置参数后执行查询 preparedStatement.executeQuery()

  • 接下来需要将查询结果转换为我们的类(主要是反射类的操作),resultSet2Obj(resultSet, Class.forName(xNode.getResultType()));

private List resultSet2Obj(ResultSet resultSet, Class<?> clazz) {

List list = new ArrayList<>();

try {

ResultSetMetaData metaData = resultSet.getMetaData();

int columnCount = metaData.getColumnCount();

// 每次遍历行值

while (resultSet.next()) {

T obj = (T) clazz.newInstance();

for (int i = 1; i <= columnCount; i++) {

Object value = resultSet.getObject(i);

String columnName = metaData.getColumnName(i);

String setMethod = “set” + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);

Method method;

if (value instanceof Timestamp) {

method = clazz.getMethod(setMethod, Date.class);

} else {

method = clazz.getMethod(setMethod, value.getClass());

}

method.invoke(obj, value);

}

list.add(obj);

}

} catch (Exception e) {

e.printStackTrace();

}

return list;

}

  • 主要通过反射生成我们的类对象,这个类的类型定义在 sql 标签上

  • 时间类型需要判断后处理,Timestamp,与 java 不是一个类型

7. Sql查询补充说明

sql 查询有入参、有不需要入参、有查询一个、有查询集合,只需要合理包装即可,例如下面的查询集合,入参是对象类型;

ApiLikeTest.test_queryUserList()

@Test

public void test_queryUserList() {

String resource = “spring/mybatis-config-datasource.xml”;

Reader reader;

try {

reader = Resources.getResourceAsReader(resource);

SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

SqlSession session = sqlMapper.openSession();

try {

User req = new User();

req.setAge(18);

List userList = session.selectList(“org.itstack.demo.dao.IUserDao.queryUserList”, req);

System.out.println(JSON.toJSONString(userList));

} finally {

session.close();

reader.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

**测试结果:

[{“age”:18,“createTime”:1576944000000,“id”:1,“name”:“水水”,“updateTime”:1576944000000},{“age”:18,“createTime”:1576944000000,“id”:2,“name”:“豆豆”,“updateTime”:1576944000000}]

Process finished with exit code 0

源码分析(mybatis)


org.mybatis

mybatis

3.4.6

Mybatis的整个源码还是很大的,以下主要将部分核心内容进行整理分析,以便于后续分析Mybatis与Spring整合的源码部分。简要包括;容器初始化、配置文件解析、Mapper加载与动态代理。

1. 从一个简单的案例开始

要学习Mybatis源码,最好的方式一定是从一个简单的点进入,而不是从Spring整合开始分析。SqlSessionFactory是整个Mybatis的核心实例对象,SqlSessionFactory对象的实例又通过SqlSessionFactoryBuilder对象来获得。SqlSessionFactoryBuilder对象可以从XML配置文件加载配置信息,然后创建SqlSessionFactory。如下例子:

MybatisApiTest.java

public class MybatisApiTest {

@Test

public void test_queryUserInfoById() {

String resource = “spring/mybatis-config-datasource.xml”;

Reader reader;

try {

reader = Resources.getResourceAsReader(resource);

SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

SqlSession session = sqlMapper.openSession();

try {

User user = session.selectOne(“org.itstack.demo.dao.IUserDao.queryUserInfoById”, 1L);

System.out.println(JSON.toJSONString(user));

} finally {

session.close();

reader.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

dao/IUserDao.java

public interface IUserDao {

User queryUserInfoById(Long id);

}

spring/mybatis-config-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>

如果一切顺利,那么会有如下结果:

{“age”:18,“createTime”:1571376957000,“id”:1,“name”:“花花”,“updateTime”:1571376957000}

从上面的代码块可以看到,核心代码;SqlSessionFactoryBuilder().build(reader),负责Mybatis配置文件的加载、解析、构建等职责,直到最终可以通过SqlSession来执行并返回结果。

2. 容器初始化

从上面代码可以看到,SqlSessionFactory是通过SqlSessionFactoryBuilder工厂类创建的,而不是直接使用构造器。容器的配置文件加载和初始化流程如下:

  • 流程核心类

  • SqlSessionFactoryBuilder

  • XMLConfigBuilder

  • XPathParser

  • Configuration

SqlSessionFactoryBuilder.java

public class SqlSessionFactoryBuilder {

public SqlSessionFactory build(Reader reader) {

return build(reader, null, null);

}

public SqlSessionFactory build(Reader reader, String environment) {

return build(reader, environment, null);

}

public SqlSessionFactory build(Reader reader, Properties properties) {

return build(reader, null, properties);

}

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {

try {

XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

return build(parser.parse());

} catch (Exception e) {

throw ExceptionFactory.wrapException(“Error building SqlSession.”, e);

} finally {

ErrorContext.instance().reset();

try {

reader.close();

} catch (IOException e) {

// Intentionally ignore. Prefer previous error.

}

}

}

public SqlSessionFactory build(InputStream inputStream) {

return build(inputStream, null, null);

}

public SqlSessionFactory build(InputStream inputStream, String environment) {

return build(inputStream, environment, null);

}

public SqlSessionFactory build(InputStream inputStream, Properties properties) {

return build(inputStream, null, properties);

}

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {

try {

XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);

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.

}

}

}

public SqlSessionFactory build(Configuration config) {

return new DefaultSqlSessionFactory(config);

}

}

从上面的源码可以看到,SqlSessionFactory提供三种方式build构建对象;

  • 字节流:java.io.InputStream

  • 字符流:java.io.Reader

  • 配置类:org.apache.ibatis.session.Configuration

那么,字节流、字符流都会创建配置文件解析类:XMLConfigBuilder,并通过parser.parse()生成Configuration,最后调用配置类构建方法生成SqlSessionFactory。

XMLConfigBuilder.java

public class XMLConfigBuilder extends BaseBuilder {

private boolean parsed;

private final XPathParser parser;

private String environment;

private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

…

public XMLConfigBuilder(Reader reader, String environment, Properties props) {

this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);

}

…

}

  1. XMLConfigBuilder对于XML文件的加载和解析都委托于XPathParser,最终使用JDK自带的javax.xml进行XML解析(XPath)

  2. XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver)

  3. reader:使用字符流创建新的输入源,用于对XML文件的读取

  4. validation:是否进行DTD校验

  5. variables:属性配置信息

  6. entityResolver:Mybatis硬编码了new XMLMapperEntityResolver()提供XML默认解析器

XMLMapperEntityResolver.java

public class XMLMapperEntityResolver implements EntityResolver {

private static final String IBATIS_CONFIG_SYSTEM = “ibatis-3-config.dtd”;

private static final String IBATIS_MAPPER_SYSTEM = “ibatis-3-mapper.dtd”;

private static final String MYBATIS_CONFIG_SYSTEM = “mybatis-3-config.dtd”;

private static final String MYBATIS_MAPPER_SYSTEM = “mybatis-3-mapper.dtd”;

private static final String MYBATIS_CONFIG_DTD = “org/apache/ibatis/builder/xml/mybatis-3-config.dtd”;

private static final String MYBATIS_MAPPER_DTD = “org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd”;

/*

  • Converts a public DTD into a local one

  • @param publicId The public id that is what comes after “PUBLIC”

  • @param systemId The system id that is what comes after the public id.

  • @return The InputSource for the DTD

  • @throws org.xml.sax.SAXException If anything goes wrong

*/

@Override

public InputSource resolveEntity(String publicId, String systemId) throws SAXException {

try {

if (systemId != null) {

String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);

if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {

return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);

} else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {

return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);

}

}

return null;

} catch (Exception e) {

throw new SAXException(e.toString());

}

}

private InputSource getInputSource(String path, String publicId, String systemId) {

InputSource source = null;

if (path != null) {

try {

InputStream in = Resources.getResourceAsStream(path);

source = new InputSource(in);

source.setPublicId(publicId);

source.setSystemId(systemId);

} catch (IOException e) {

// ignore, null is ok

}

}

return source;

}

}

  1. Mybatis依赖于dtd文件进行进行解析,其中的ibatis-3-config.dtd主要是用于兼容用途

  2. getInputSource(String path, String publicId, String systemId)的调用里面有两个参数publicId(公共标识符)和systemId(系统标示符)

XPathParser.java

public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {

commonConstructor(validation, variables, entityResolver);

this.document = createDocument(new InputSource(reader));

}

private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {

this.validation = validation;

this.entityResolver = entityResolver;

this.variables = variables;

XPathFactory factory = XPathFactory.newInstance();

this.xpath = factory.newXPath();

}

private Document createDocument(InputSource inputSource) {

// important: this must only be called AFTER common constructor

try {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

factory.setValidating(validation);

factory.setNamespaceAware(false);

factory.setIgnoringComments(true);

factory.setIgnoringElementContentWhitespace(false);

factory.setCoalescing(false);

factory.setExpandEntityReferences(true);

DocumentBuilder builder = factory.newDocumentBuilder();

builder.setEntityResolver(entityResolver);

builder.setErrorHandler(new ErrorHandler() {

@Override

public void error(SAXParseException exception) throws SAXException {

throw exception;

}

@Override

public void fatalError(SAXParseException exception) throws SAXException {

throw exception;

}

@Override

public void warning(SAXParseException exception) throws SAXException {

}

});

return builder.parse(inputSource);

} catch (Exception e) {

throw new BuilderException("Error creating document instance. Cause: " + e, e);

}

}

  1. 从上到下可以看到主要是为了创建一个Mybatis的文档解析器,最后根据builder.parse(inputSource)返回Document

  2. 得到XPathParser实例后,接下来在调用方法:this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);

XMLConfigBuilder.this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);

private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {

super(new Configuration());

ErrorContext.instance().resource(“SQL Mapper Configuration”);

this.configuration.setVariables(props);

this.parsed = false;

this.environment = environment;

this.parser = parser;

}

  1. 其中调用了父类的构造函数

public abstract class BaseBuilder {

protected final Configuration configuration;

protected final TypeAliasRegistry typeAliasRegistry;

protected final TypeHandlerRegistry typeHandlerRegistry;

public BaseBuilder(Configuration configuration) {

this.configuration = configuration;

this.typeAliasRegistry = this.configuration.getTypeAliasRegistry();

this.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();

}

}

  1. XMLConfigBuilder创建完成后,sqlSessionFactoryBuild调用parser.parse()创建Configuration

public class XMLConfigBuilder extends BaseBuilder {

public Configuration parse() {

if (parsed) {

throw new BuilderException(“Each XMLConfigBuilder can only be used once.”);

}

parsed = true;

parseConfiguration(parser.evalNode(“/configuration”));

return configuration;

}

}

3. 配置文件解析

这一部分是整个XML文件解析和装载的核心内容,其中包括;

  1. 属性解析propertiesElement

  2. 加载settings节点settingsAsProperties

  3. 载自定义VFS loadCustomVfs

  4. 解析类型别名typeAliasesElement

  5. 加载插件pluginElement

  6. 加载对象工厂objectFactoryElement

  7. 创建对象包装器工厂objectWrapperFactoryElement

  8. 加载反射工厂reflectorFactoryElement

  9. 元素设置settingsElement

  10. 加载环境配置environmentsElement

  11. 数据库厂商标识加载databaseIdProviderElement

  12. 加载类型处理器typeHandlerElement

  13. (核心)加载mapper文件mapperElement

parseConfiguration(parser.evalNode(“/configuration”));

private void parseConfiguration(XNode root) {

try {

//issue #117 read properties first

//属性解析propertiesElement

propertiesElement(root.evalNode(“properties”));

//加载settings节点settingsAsProperties

Properties settings = settingsAsProperties(root.evalNode(“settings”));

//加载自定义VFS loadCustomVfs

loadCustomVfs(settings);

//解析类型别名typeAliasesElement

typeAliasesElement(root.evalNode(“typeAliases”));

//加载插件pluginElement

pluginElement(root.evalNode(“plugins”));

//加载对象工厂objectFactoryElement

objectFactoryElement(root.evalNode(“objectFactory”));

//创建对象包装器工厂objectWrapperFactoryElement

objectWrapperFactoryElement(root.evalNode(“objectWrapperFactory”));

//加载反射工厂reflectorFactoryElement

reflectorFactoryElement(root.evalNode(“reflectorFactory”));

//元素设置

settingsElement(settings);

// read it after objectFactory and objectWrapperFactory issue #631

//加载环境配置environmentsElement

environmentsElement(root.evalNode(“environments”));

//数据库厂商标识加载databaseIdProviderElement

databaseIdProviderElement(root.evalNode(“databaseIdProvider”));

//加载类型处理器typeHandlerElement

typeHandlerElement(root.evalNode(“typeHandlers”));

//加载mapper文件mapperElement

mapperElement(root.evalNode(“mappers”));

} catch (Exception e) {

throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);

}

}

所有的root.evalNode()底层都是调用XML DOM方法:Object evaluate(String expression, Object item, QName returnType),表达式参数expression,通过XObject resultObject = eval( expression, item )返回最终节点内容,可以参考http://mybatis.org/dtd/mybatis-3-config.dtd,如下;

<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)> <!ELEMENT databaseIdProvider (property*)> <!ATTLIST databaseIdProvider type CDATA #REQUIRED > <!ELEMENT properties (property*)> <!ATTLIST properties resource CDATA #IMPLIED url CDATA #IMPLIED > <!ELEMENT property EMPTY> <!ATTLIST property name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT settings (setting+)> <!ELEMENT setting EMPTY> <!ATTLIST setting name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT typeAliases (typeAlias*,package*)> <!ELEMENT typeAlias EMPTY> <!ATTLIST typeAlias type CDATA #REQUIRED alias CDATA #IMPLIED > <!ELEMENT typeHandlers (typeHandler*,package*)> <!ELEMENT typeHandler EMPTY> <!ATTLIST typeHandler javaType CDATA #IMPLIED jdbcType CDATA #IMPLIED handler CDATA #REQUIRED > <!ELEMENT objectFactory (property*)> <!ATTLIST objectFactory type CDATA #REQUIRED > <!ELEMENT objectWrapperFactory EMPTY> <!ATTLIST objectWrapperFactory type CDATA #REQUIRED > <!ELEMENT reflectorFactory EMPTY> <!ATTLIST reflectorFactory type CDATA #REQUIRED > <!ELEMENT plugins (plugin+)> <!ELEMENT plugin (property*)> <!ATTLIST plugin interceptor CDATA #REQUIRED > <!ELEMENT environments (environment+)> <!ATTLIST environments default CDATA #REQUIRED > <!ELEMENT environment (transactionManager,dataSource)> <!ATTLIST environment id CDATA #REQUIRED > <!ELEMENT transactionManager (property*)> <!ATTLIST transactionManager type CDATA #REQUIRED > <!ELEMENT dataSource (property*)> <!ATTLIST dataSource type CDATA #REQUIRED > <!ELEMENT mappers (mapper*,package*)> <!ELEMENT mapper EMPTY> <!ATTLIST mapper resource CDATA #IMPLIED url CDATA #IMPLIED class CDATA #IMPLIED > <!ELEMENT package EMPTY> <!ATTLIST package name CDATA #REQUIRED >

mybatis-3-config.dtd 定义文件中有11个配置文件,如下;

  1. properties?,

  2. settings?,

  3. typeAliases?,

  4. typeHandlers?,

  5. objectFactory?,

  6. objectWrapperFactory?,

  7. reflectorFactory?,

  8. plugins?,

  9. environments?,

  10. databaseIdProvider?,

  11. mappers?

以上每个配置都是可选。最终配置内容会保存到org.apache.ibatis.session.Configuration,如下;

public class Configuration {

protected Environment environment;

// 允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为false。默认为false

protected boolean safeRowBoundsEnabled;

// 允许在嵌套语句中使用分页(ResultHandler)。如果允许使用则设置为false。

protected boolean safeResultHandlerEnabled = true;

// 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。默认false

protected boolean mapUnderscoreToCamelCase;

// 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载。默认值false (true in ≤3.4.1)

protected boolean aggressiveLazyLoading;

// 是否允许单一语句返回多结果集(需要兼容驱动)。

protected boolean multipleResultSetsEnabled = true;

// 允许 JDBC 支持自动生成主键,需要驱动兼容。这就是insert时获取mysql自增主键/oracle sequence的开关。注:一般来说,这是希望的结果,应该默认值为true比较合适。

protected boolean useGeneratedKeys;

// 使用列标签代替列名,一般来说,这是希望的结果

protected boolean useColumnLabel = true;

// 是否启用缓存 {默认是开启的,可能这也是你的面试题}

protected boolean cacheEnabled = true;

// 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。

protected boolean callSettersOnNulls;

// 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的工程必须采用Java 8编译,并且加上-parameters选项。(从3.4.1开始)

protected boolean useActualParamName = true;

//当返回行的所有列都是空时,MyBatis默认返回null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集 (i.e. collectioin and association)。(从3.4.2开始) 注:这里应该拆分为两个参数比较合适, 一个用于结果集,一个用于单记录。通常来说,我们会希望结果集不是null,单记录仍然是null

protected boolean returnInstanceForEmptyRow;

// 指定 MyBatis 增加到日志名称的前缀。

protected String logPrefix;

// 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。一般建议指定为slf4j或log4j

protected Class <? extends Log> logImpl;

// 指定VFS的实现, VFS是mybatis提供的用于访问AS内资源的一个简便接口

protected Class <? extends VFS> vfsImpl;

// MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。

protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;

// 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。

protected JdbcType jdbcTypeForNull = JdbcType.OTHER;

// 指定对象的哪个方法触发一次延迟加载。

protected Set lazyLoadTriggerMethods = new HashSet(Arrays.asList(new String[] { “equals”, “clone”, “hashCode”, “toString” }));

// 设置超时时间,它决定驱动等待数据库响应的秒数。默认不超时

protected Integer defaultStatementTimeout;

// 为驱动的结果集设置默认获取数量。

protected Integer defaultFetchSize;

// SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。

protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;

// 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。

protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;

// 指定发现自动映射目标未知列(或者未知属性类型)的行为。这个值应该设置为WARNING比较合适

protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;

// settings下的properties属性

protected Properties variables = new Properties();

// 默认的反射器工厂,用于操作属性、构造器方便

protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();

// 对象工厂, 所有的类resultMap类都需要依赖于对象工厂来实例化

protected ObjectFactory objectFactory = new DefaultObjectFactory();

// 对象包装器工厂,主要用来在创建非原生对象,比如增加了某些监控或者特殊属性的代理类

protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();

// 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。

protected boolean lazyLoadingEnabled = false;

// 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。MyBatis 3.3+使用JAVASSIST

protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL

// MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。

protected String databaseId;

…

}

以上可以看到,Mybatis把所有的配置;resultMap、Sql语句、插件、缓存等都维护在Configuration中。这里还有一个小技巧,在Configuration还有一个StrictMap内部类,它继承于HashMap完善了put时防重、get时取不到值的异常处理,如下;

protected static class StrictMap extends HashMap<String, V> {

private static final long serialVersionUID = -4950446264854982944L;

private final String name;

public StrictMap(String name, int initialCapacity, float loadFactor) {

super(initialCapacity, loadFactor);

this.name = name;

}

public StrictMap(String name, int initialCapacity) {

super(initialCapacity);

this.name = name;

}

public StrictMap(String name) {

super();

this.name = name;

}

public StrictMap(String name, Map<String, ? extends V> m) {

super(m);

this.name = name;

}

}

(核心)加载mapper文件mapperElement

Mapper文件处理是Mybatis框架的核心服务,所有的SQL语句都编写在Mapper中,这块也是我们分析的重点,其他模块可以后续讲解。

XMLConfigBuilder.parseConfiguration()->mapperElement(root.evalNode(“mappers”));

private void mapperElement(XNode parent) throws Exception {

if (parent != null) {

for (XNode child : parent.getChildren()) {

// 如果要同时使用package自动扫描和通过mapper明确指定要加载的mapper,一定要确保package自动扫描的范围不包含明确指定的mapper,否则在通过package扫描的interface的时候,尝试加载对应xml文件的loadXmlResource()的逻辑中出现判重出错,报org.apache.ibatis.binding.BindingException异常,即使xml文件中包含的内容和mapper接口中包含的语句不重复也会出错,包括加载mapper接口时自动加载的xml mapper也一样会出错。

if (“package”.equals(child.getName())) {

String mapperPackage = child.getStringAttribute(“name”);

configuration.addMappers(mapperPackage);

} else {

String resource = child.getStringAttribute(“resource”);

String url = child.getStringAttribute(“url”);

String mapperClass = child.getStringAttribute(“class”);

if (resource != null && url == null && mapperClass == null) {

ErrorContext.instance().resource(resource);

InputStream inputStream = Resources.getResourceAsStream(resource);

XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());

mapperParser.parse();

} else if (resource == null && url != null && mapperClass == null) {

ErrorContext.instance().resource(url);

InputStream inputStream = Resources.getUrlAsStream(url);

XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());

mapperParser.parse();

} else if (resource == null && url == null && mapperClass != null) {

Class<?> mapperInterface = Resources.classForName(mapperClass);

configuration.addMapper(mapperInterface);

} else {

throw new BuilderException(“A mapper element may only specify a url, resource or class, but not more than one.”);

}

}

}

}

}

  • Mybatis提供了两类配置Mapper的方法,第一类是使用package自动搜索的模式,这样指定package下所有接口都会被注册为mapper,也是在Spring中比较常用的方式,例如:
  • 另外一类是明确指定Mapper,这又可以通过resource、url或者class进行细分,例如;

4. Mapper加载与动态代理

通过package方式自动搜索加载,生成对应的mapper代理类,代码块和流程,如下;

private void mapperElement(XNode parent) throws Exception {

if (parent != null) {

for (XNode child : parent.getChildren()) {

if (“package”.equals(child.getName())) {

String mapperPackage = child.getStringAttribute(“name”);

configuration.addMappers(mapperPackage);

} else {

…

}

}

}

}

Mapper加载到生成代理对象的流程中,主要的核心类包括;

  1. XMLConfigBuilder

  2. Configuration

  3. MapperRegistry

  4. MapperAnnotationBuilder

  5. MapperProxyFactory

MapperRegistry.java

解析加载Mapper

public void addMappers(String packageName, Class<?> superType) {

// mybatis框架提供的搜索classpath下指定package以及子package中符合条件(注解或者继承于某个类/接口)的类,默认使用Thread.currentThread().getContextClassLoader()返回的加载器,和spring的工具类殊途同归。

ResolverUtil<Class<?>> resolverUtil = new ResolverUtil

// 无条件的加载所有的类,因为调用方传递了Object.class作为父类,这也给以后的指定mapper接口预留了余地

resolverUtil.find(new ResolverUtil.IsA(superType), packageName);

// 所有匹配的calss都被存储在ResolverUtil.matches字段中

Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();

for (Class<?> mapperClass : mapperSet) {

//调用addMapper方法进行具体的mapper类/接口解析

addMapper(mapperClass);

}

}

生成代理类:MapperProxyFactory

public void addMapper(Class type) {

// 对于mybatis mapper接口文件,必须是interface,不能是class

if (type.isInterface()) {

if (hasMapper(type)) {

throw new BindingException(“Type " + type + " is already known to the MapperRegistry.”);

}

boolean loadCompleted = false;

try {

// 为mapper接口创建一个MapperProxyFactory代理

knownMappers.put(type, new MapperProxyFactory(type));

// It’s important that the type is added before the parser is run

// otherwise the binding may automatically be attempted by the

// mapper parser. If the type is already known, it won’t try.

MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);

parser.parse();

loadCompleted = true;

} finally {

if (!loadCompleted) {

knownMappers.remove(type);

}

}

}

}

在MapperRegistry中维护了接口类与代理工程的映射关系,knownMappers;

private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

MapperProxyFactory.java

public class MapperProxyFactory {

private final Class mapperInterface;

private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

public MapperProxyFactory(Class mapperInterface) {

this.mapperInterface = mapperInterface;

}

public Class getMapperInterface() {

return mapperInterface;

}

public Map<Method, MapperMethod> getMethodCache() {

return methodCache;

}

@SuppressWarnings(“unchecked”)

protected T newInstance(MapperProxy mapperProxy) {

return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);

}

public T newInstance(SqlSession sqlSession) {

final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);

return newInstance(mapperProxy);

}

}

如上是Mapper的代理类工程,构造函数中的mapperInterface就是对应的接口类,当实例化时候会获得具体的MapperProxy代理,里面主要包含了SqlSession。

源码分析(mybatis-spring)


org.mybatis

mybatis-spring

1.3.2

作为一款好用的ORM框架,一定是萝莉脸(单纯)、御姐心(强大),铺的了床(屏蔽与JDBC直接打交道)、暖的了房(速度性能好)!鉴于这些优点几乎在国内互联网大部分开发框架都会使用到Mybatis,尤其在一些需要高性能的场景下需要优化sql那么一定需要手写sql在xml中。那么,准备好了吗!开始分析分析它的源码;

1. 从一个简单的案例开始

与分析mybatis源码一样,先做一个简单的案例;定义dao、编写配置文件、junit单元测试;

SpringApiTest.java

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(“classpath:spring-config.xml”)

public class SpringApiTest {

private Logger logger = LoggerFactory.getLogger(SpringApiTest.class);

@Resource

private ISchoolDao schoolDao;

@Resource

private IUserDao userDao;

@Test

public void test_queryRuleTreeByTreeId(){

School ruleTree = schoolDao.querySchoolInfoById(1L);

logger.info(JSON.toJSONString(ruleTree));

User user = userDao.queryUserInfoById(1L);

logger.info(JSON.toJSONString(user));

}

}

spring-config-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

如果一切顺利,那么会有如下结果:

{“address”:“北京市海淀区颐和园路5号”,“createTime”:1571376957000,“id”:1,“name”:“北京大学”,“updateTime”:1571376957000}

{“age”:18,“createTime”:1571376957000,“id”:1,“name”:“花花”,“updateTime”:1571376957000}

从上面单元测试的代码可以看到,两个没有方法体的注解就这么神奇的执行了我们的xml中的配置语句并输出了结果。其实主要得益于以下两个类;

  • org.mybatis.spring.SqlSessionFactoryBean

  • org.mybatis.spring.mapper.MapperScannerConfigurer

2. 扫描装配注册(MapperScannerConfigurer)

MapperScannerConfigurer为整个Dao接口层生成动态代理类注册,启动到了核心作用。这个类实现了如下接口,用来对扫描的Mapper进行处理:

  • BeanDefinitionRegistryPostProcessor

  • InitializingBean

  • ApplicationContextAware

  • BeanNameAware

整体类图如下;

执行流程如下;

上面的类图+流程图,其实已经很清楚的描述了MapperScannerConfigurer初始化过程,但对于头一次看的新人来说依旧是我太难了,好继续!

MapperScannerConfigurer.java & 部分截取

@Override

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {

if (this.processPropertyPlaceHolders) {

processPropertyPlaceHolders();

}

ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);

scanner.setAddToConfig(this.addToConfig);

scanner.setAnnotationClass(this.annotationClass);

scanner.setMarkerInterface(this.markerInterface);

scanner.setSqlSessionFactory(this.sqlSessionFactory);

scanner.setSqlSessionTemplate(this.sqlSessionTemplate);

scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);

scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);

scanner.setResourceLoader(this.applicationContext);

scanner.setBeanNameGenerator(this.nameGenerator);

scanner.registerFilters();

scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));

}

  • 实现了BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry用于注册Bean到Spring容器中

  • 306行:new ClassPathMapperScanner(registry); 硬编码类路径扫描器,用于解析Mybatis的Mapper文件

  • 317行:scanner.scan 对Mapper进行扫描。这里包含了一个继承类实现关系的调用,也就是本文开头的测试题。

ClassPathMapperScanner.java & 部分截取

@Override

public Set doScan(String… basePackages) {

Set beanDefinitions = super.doScan(basePackages);

if (beanDefinitions.isEmpty()) {

logger.warn(“No MyBatis mapper was found in '” + Arrays.toString(basePackages) + “’ package. Please check your configuration.”);

} else {

processBeanDefinitions(beanDefinitions);

}

return beanDefinitions;

}

  • 优先调用父类的super.doScan(basePackages);进行注册Bean信息

ClassPathBeanDefinitionScanner.java & 部分截取

protected Set doScan(String… basePackages) {

Assert.notEmpty(basePackages, “At least one base package must be specified”);

Set beanDefinitions = new LinkedHashSet();

for (String basePackage : basePackages) {

Set candidates = findCandidateComponents(basePackage);

for (BeanDefinition candidate : candidates) {

ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);

candidate.setScope(scopeMetadata.getScopeName());

String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);

if (candidate instanceof AbstractBeanDefinition) {

postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);

}

if (candidate instanceof AnnotatedBeanDefinition) {

AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate)

}

if (checkCandidate(beanName, candidate)) {

BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);

definitionHolder =

AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.regi

beanDefinitions.add(definitionHolder);

registerBeanDefinition(definitionHolder, this.registry);

}

}

}

return beanDefinitions;

}

  • 优先调用了父类的doScan方法,用于Mapper扫描和Bean的定义以及注册到DefaultListableBeanFactory。{DefaultListableBeanFactory是Spring中IOC容器的始祖,所有需要实例化的类都需要注册进来,之后在初始化}

  • 272行:findCandidateComponents(basePackage),扫描package包路径,对于注解类的有另外的方式,大同小异

  • 288行:registerBeanDefinition(definitionHolder, this.registry);注册Bean信息的过程,最终会调用到:org.springframework.beans.factory.support.DefaultListableBeanFactory

ClassPathMapperScanner.java & 部分截取

processBeanDefinitions(beanDefinitions);

private void processBeanDefinitions(Set beanDefinitions) {

GenericBeanDefinition definition;

for (BeanDefinitionHolder holder : beanDefinitions) {

definition = (GenericBeanDefinition) holder.getBeanDefinition();

if (logger.isDebugEnabled()) {

logger.debug(“Creating MapperFactoryBean with name '” + holder.getBeanName()

  • “’ and '” + definition.getBeanClassName() + “’ mapperInterface”);

}

// the mapper interface is the original class of the bean

// but, the actual class of the bean is MapperFactoryBean

definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59

definition.setBeanClass(this.mapperFactoryBean.getClass());

definition.getPropertyValues().add(“addToConfig”, this.addToConfig);

boolean explicitFactoryUsed = false;

if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {

definition.getPropertyValues().add(“sqlSessionFactory”, new RuntimeBeanReference(this.sqlSessionFactoryBeanName));

explicitFactoryUsed = true;

} else if (this.sqlSessionFactory != null) {

definition.getPropertyValues().add(“sqlSessionFactory”, this.sqlSessionFactory);

explicitFactoryUsed = true;

}

if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {

if (explicitFactoryUsed) {

logger.warn(“Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.”);

}

definition.getPropertyValues().add(“sqlSessionTemplate”, new RuntimeBeanReference(this.sqlSessionTemplateBeanName));

explicitFactoryUsed = true;

} else if (this.sqlSessionTemplate != null) {

if (explicitFactoryUsed) {

logger.warn(“Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.”);

}

definition.getPropertyValues().add(“sqlSessionTemplate”, this.sqlSessionTemplate);

explicitFactoryUsed = true;

}

if (!explicitFactoryUsed) {

if (logger.isDebugEnabled()) {

logger.debug(“Enabling autowire by type for MapperFactoryBean with name '” + holder.getBeanName() + “'.”);

}

definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

}

}

}

  • 163行:super.doScan(basePackages);,调用完父类方法后开始执行内部方法:processBeanDefinitions(beanDefinitions)

  • 186行:definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); 设置BeanName参数,也就是我们的:ISchoolDao、IUserDao

  • 187行:definition.setBeanClass(this.mapperFactoryBean.getClass());,设置BeanClass,接口本身是没有类的,那么这里将MapperFactoryBean类设置进来,最终所有的dao层接口类都是这个MapperFactoryBean

MapperFactoryBean.java & 部分截取

这个类有继承也有接口实现,最好先了解下整体类图,如下;

这个类就非常重要了,最终所有的sql信息执行都会通过这个类获取getObject(),也就是SqlSession获取mapper的代理类:MapperProxyFactory->MapperProxy

public class MapperFactoryBean extends SqlSessionDaoSupport implements FactoryBean {

private Class mapperInterface;

private boolean addToConfig = true;

public MapperFactoryBean() {

//intentionally empty

}

public MapperFactoryBean(Class mapperInterface) {

this.mapperInterface = mapperInterface;

}

/**

  • 当SpringBean容器初始化时候会调用到checkDaoConfig(),他是继承类中的抽象方法

  • {@inheritDoc}

*/

@Override

protected void checkDaoConfig() {

super.checkDaoConfig();

notNull(this.mapperInterface, “Property ‘mapperInterface’ is required”);

Configuration configuration = getSqlSession().getConfiguration();

if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {

try {

configuration.addMapper(this.mapperInterface);

} catch (Exception e) {

logger.error(“Error while adding the mapper '” + this.mapperInterface + “’ to configuration.”, e);

throw new IllegalArgumentException(e);

} finally {

ErrorContext.instance().reset();

}

}

}

/**

  • {@inheritDoc}

*/

@Override

public T getObject() throws Exception {

return getSqlSession().getMapper(this.mapperInterface);

}

…

}

  • 72行:checkDaoConfig(),当SpringBean容器初始化时候会调用到checkDaoConfig(),他是继承类中的抽象方法

  • 95行:getSqlSession().getMapper(this.mapperInterface);,通过接口获取Mapper(代理类),调用过程如下;

  • DefaultSqlSession.getMapper(Class type),获取Mapper

  • Configuration.getMapper(Class type, SqlSession sqlSession),从配置中获取

  • MapperRegistry.getMapper(Class type, SqlSession sqlSession),从注册中心获取到实例化生成

public T getMapper(Class type, SqlSession sqlSession) {

final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) knownMappers.get(type);

if (mapperProxyFactory == null) {

throw new BindingException(“Type " + type + " is not known to the MapperRegistry.”);

}

try {

return mapperProxyFactory.newInstance(sqlSession);

} catch (Exception e) {

throw new BindingException("Error getting mapper instance. Cause: " + e, e);

}

}

  • mapperProxyFactory.newInstance(sqlSession);,通过反射工程生成MapperProxy

@SuppressWarnings(“unchecked”)

protected T newInstance(MapperProxy mapperProxy) {

return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);

}

public T newInstance(SqlSession sqlSession) {

final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);

return newInstance(mapperProxy);

}

MapperProxy.java & 部分截取

public class MapperProxy implements InvocationHandler, Serializable {

private static final long serialVersionUID = -6424540398559729838L;

private final SqlSession sqlSession;

private final Class mapperInterface;

private final Map<Method, MapperMethod> methodCache;

public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map<Method, MapperMethod> methodCache) {

this.sqlSession = sqlSession;

this.mapperInterface = mapperInterface;

this.methodCache = methodCache;

}

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

try {

if (Object.class.equals(method.getDeclaringClass())) {

return method.invoke(this, args);

} else if (isDefaultMethod(method)) {

return invokeDefaultMethod(proxy, method, args);

}

} catch (Throwable t) {

throw ExceptionUtil.unwrapThrowable(t);

}

final MapperMethod mapperMethod = cachedMapperMethod(method);

return mapperMethod.execute(sqlSession, args);

}

private MapperMethod cachedMapperMethod(Method method) {

MapperMethod mapperMethod = methodCache.get(method);

if (mapperMethod == null) {

mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());

methodCache.put(method, mapperMethod);

}

return mapperMethod;

}

@UsesJava7

private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)

throws Throwable {

final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class

.getDeclaredConstructor(Class.class, int.class);

if (!constructor.isAccessible()) {

constructor.setAccessible(true);

}

final Class<?> declaringClass = method.getDeclaringClass();

return constructor

.newInstance(declaringClass,

MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED

| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)

.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);

}

…

}

  • 58行:final MapperMethod mapperMethod = cachedMapperMethod(method);,从缓存中获取MapperMethod

  • 59行:mapperMethod.execute(sqlSession, args);,执行SQL语句,并返回结果(到这关于查询获取结果就到骨头(干)层了);INSERT、UPDATE、DELETE、SELECT

public Object execute(SqlSession sqlSession, Object[] args) {

Object result;

switch (command.getType()) {

case INSERT: {

Object param = method.convertArgsToSqlCommandParam(args);

result = rowCountResult(sqlSession.insert(command.getName(), param));

break;

}

case UPDATE: {

Object param = method.convertArgsToSqlCommandParam(args);

result = rowCountResult(sqlSession.update(command.getName(), param));

break;

}

case DELETE: {

Object param = method.convertArgsToSqlCommandParam(args);

result = rowCountResult(sqlSession.delete(command.getName(), param));

break;

}

case SELECT:

if (method.returnsVoid() && method.hasResultHandler()) {

executeWithResultHandler(sqlSession, args);

result = null;

} else if (method.returnsMany()) {

result = executeForMany(sqlSession, args);

} else if (method.returnsMap()) {

result = executeForMap(sqlSession, args);

} else if (method.returnsCursor()) {

result = executeForCursor(sqlSession, args);

} else {

Object param = method.convertArgsToSqlCommandParam(args);

result = sqlSession.selectOne(command.getName(), param);

}

break;

case FLUSH:

result = sqlSession.flushStatements();

break;

default:

throw new BindingException("Unknown execution method for: " + command.getName());

}

if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {

throw new BindingException(“Mapper method '” + command.getName()

+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + “).”);

}

return result;

}

以上对于MapperScannerConfigurer这一层就分析完了,从扫描定义注入到为Spring容器准备Bean的信息,代理、反射、SQL执行,基本就包括全部核心内容了,接下来在分析下SqlSessionFactoryBean

3. SqlSession容器工厂初始化(SqlSessionFactoryBean)

SqlSessionFactoryBean初始化过程中需要对一些自身内容进行处理,因此也需要实现如下接口;

  • FactoryBean

  • InitializingBean -> void afterPropertiesSet() throws Exception

  • ApplicationListener

以上的流程其实已经很清晰的描述整个核心流程,但同样对于新手上路会有障碍,那么!好,继续!

SqlSessionFactoryBean.java & 部分截取

public void afterPropertiesSet() throws Exception {

notNull(dataSource, “Property ‘dataSource’ is required”);

notNull(sqlSessionFactoryBuilder, “Property ‘sqlSessionFactoryBuilder’ is required”);

state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),

“Property ‘configuration’ and ‘configLocation’ can not specified with together”);

this.sqlSessionFactory = buildSqlSessionFactory();

}

  • afterPropertiesSet(),InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。

  • 380行:buildSqlSessionFactory();内部方法构建,核心功能继续往下看。

SqlSessionFactoryBean.java & 部分截取

protected SqlSessionFactory buildSqlSessionFactory() throws IOException {

Configuration configuration;

XMLConfigBuilder xmlConfigBuilder = null;

…

if (!isEmpty(this.mapperLocations)) {

for (Resource mapperLocation : this.mapperLocations) {

if (mapperLocation == null) {

continue;

}

try {

XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),

configuration, mapperLocation.toString(), configuration.getSqlFragments());

xmlMapperBuilder.parse();

} catch (Exception e) {

throw new NestedIOException(“Failed to parse mapping resource: '” + mapperLocation + “'”, e);

} finally {

ErrorContext.instance().reset();

}

if (LOGGER.isDebugEnabled()) {

LOGGER.debug(“Parsed mapper file: '” + mapperLocation + “'”);

}

}

} else {

if (LOGGER.isDebugEnabled()) {

LOGGER.debug(“Property ‘mapperLocations’ was not specified or no matching resources found”);

}

}

return this.sqlSessionFactoryBuilder.build(configuration);

}

  • 513行:for (Resource mapperLocation : this.mapperLocations) 循环解析Mapper内容

  • 519行:XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(…) 解析XMLMapperBuilder

  • 521行:xmlMapperBuilder.parse() 执行解析,具体如下;

XMLMapperBuilder.java & 部分截取

public class XMLMapperBuilder extends BaseBuilder {

private final XPathParser parser;

private final MapperBuilderAssistant builderAssistant;

private final Map<String, XNode> sqlFragments;

private final String resource;

private void bindMapperForNamespace() {

String namespace = builderAssistant.getCurrentNamespace();

if (namespace != null) {

Class<?> boundType = null;

try {

boundType = Resources.classForName(namespace);

} catch (ClassNotFoundException e) {

//ignore, bound type is not required

}

if (boundType != null) {

if (!configuration.hasMapper(boundType)) {

// Spring may not know the real resource name so we set a flag

// to prevent loading again this resource from the mapper interface

// look at MapperAnnotationBuilder#loadXmlResource

configuration.addLoadedResource(“namespace:” + namespace);

configuration.addMapper(boundType);

}

}

}

}

}

  • 这里413行非常重要,configuration.addMapper(boundType);,真正到了添加Mapper到配置中心

MapperRegistry.java & 部分截取

public class MapperRegistry {

public void addMapper(Class type) {

if (type.isInterface()) {

if (hasMapper(type)) {

throw new BindingException(“Type " + type + " is already known to the MapperRegistry.”);

}

boolean loadCompleted = false;

try {

knownMappers.put(type, new MapperProxyFactory(type));

// It’s important that the type is added before the parser is run

// otherwise the binding may automatically be attempted by the

// mapper parser. If the type is already known, it won’t try.

MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);

parser.parse();

loadCompleted = true;

} finally {

if (!loadCompleted) {

knownMappers.remove(type);

}

}

}

}

}

  • 67行:创建代理工程knownMappers.put(type, new MapperProxyFactory(type));

截至到这,MapperScannerConfigurer、SqlSessionFactoryBean,两个类干的事情就相融合了;

  • 第一个用于扫描Dao接口设置代理类注册到IOC中,用于后续生成Bean实体类,MapperFactoryBean,并可以通过mapperInterface从Configuration获取Mapper

  • 另一个用于生成SqlSession工厂初始化,解析Mapper里的XML配置进行动态代理MapperProxyFactory->MapperProxy注入到Configuration的Mapper

  • 最终在注解类的帮助下进行方法注入,等执行操作时候即可获得动态代理对象,从而执行相应的CRUD操作

@Resource

private ISchoolDao schoolDao;

schoolDao.querySchoolInfoById(1L);

最后

做任何事情都要用心,要非常关注细节。看起来不起眼的、繁琐的工作做透了会有意想不到的价值。
当然要想成为一个技术大牛也需要一定的思想格局,思想决定未来你要往哪个方向去走, 建议多看一些人生规划方面的书籍,多学习名人的思想格局,未来你的路会走的更远。

更多的技术点思维导图我已经做了一个整理,涵盖了当下互联网最流行99%的技术点,在这里我将这份导图分享出来,以及为金九银十准备的一整套面试体系,上到集合,下到分布式微服务

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
apperBuilder(…) 解析XMLMapperBuilder

  • 521行:xmlMapperBuilder.parse() 执行解析,具体如下;

XMLMapperBuilder.java & 部分截取

public class XMLMapperBuilder extends BaseBuilder {

private final XPathParser parser;

private final MapperBuilderAssistant builderAssistant;

private final Map<String, XNode> sqlFragments;

private final String resource;

private void bindMapperForNamespace() {

String namespace = builderAssistant.getCurrentNamespace();

if (namespace != null) {

Class<?> boundType = null;

try {

boundType = Resources.classForName(namespace);

} catch (ClassNotFoundException e) {

//ignore, bound type is not required

}

if (boundType != null) {

if (!configuration.hasMapper(boundType)) {

// Spring may not know the real resource name so we set a flag

// to prevent loading again this resource from the mapper interface

// look at MapperAnnotationBuilder#loadXmlResource

configuration.addLoadedResource(“namespace:” + namespace);

configuration.addMapper(boundType);

}

}

}

}

}

  • 这里413行非常重要,configuration.addMapper(boundType);,真正到了添加Mapper到配置中心

MapperRegistry.java & 部分截取

public class MapperRegistry {

public void addMapper(Class type) {

if (type.isInterface()) {

if (hasMapper(type)) {

throw new BindingException(“Type " + type + " is already known to the MapperRegistry.”);

}

boolean loadCompleted = false;

try {

knownMappers.put(type, new MapperProxyFactory(type));

// It’s important that the type is added before the parser is run

// otherwise the binding may automatically be attempted by the

// mapper parser. If the type is already known, it won’t try.

MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);

parser.parse();

loadCompleted = true;

} finally {

if (!loadCompleted) {

knownMappers.remove(type);

}

}

}

}

}

  • 67行:创建代理工程knownMappers.put(type, new MapperProxyFactory(type));

截至到这,MapperScannerConfigurer、SqlSessionFactoryBean,两个类干的事情就相融合了;

  • 第一个用于扫描Dao接口设置代理类注册到IOC中,用于后续生成Bean实体类,MapperFactoryBean,并可以通过mapperInterface从Configuration获取Mapper

  • 另一个用于生成SqlSession工厂初始化,解析Mapper里的XML配置进行动态代理MapperProxyFactory->MapperProxy注入到Configuration的Mapper

  • 最终在注解类的帮助下进行方法注入,等执行操作时候即可获得动态代理对象,从而执行相应的CRUD操作

@Resource

private ISchoolDao schoolDao;

schoolDao.querySchoolInfoById(1L);

最后

做任何事情都要用心,要非常关注细节。看起来不起眼的、繁琐的工作做透了会有意想不到的价值。
当然要想成为一个技术大牛也需要一定的思想格局,思想决定未来你要往哪个方向去走, 建议多看一些人生规划方面的书籍,多学习名人的思想格局,未来你的路会走的更远。

更多的技术点思维导图我已经做了一个整理,涵盖了当下互联网最流行99%的技术点,在这里我将这份导图分享出来,以及为金九银十准备的一整套面试体系,上到集合,下到分布式微服务

[外链图片转存中…(img-0AW3X6mj-1714708086653)]

[外链图片转存中…(img-Fs7BE9gc-1714708086653)]

[外链图片转存中…(img-NMKhOL92-1714708086654)]

[外链图片转存中…(img-fyExQQup-1714708086654)]

《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!

YOLOv11涨点改进| TGRS 2026 | 独家创新首发、特征融合改进篇| 引入STSAM协同时空注意力融合模块,发论文热点创新,注意力能够互相引导强化边界和结构细节,增强目标检测、图像分割涨点 🔥本文提出了一种改进YOLOv11网络模型的STSAM协同时空注意力融合模块,用于提升高分辨率遥感变化检测的精度。STSAM通过并行处理全局跨时相注意力和局部坐标注意力,能有效聚焦真实变化目标,强化边界和结构细节。该模块包含两个分支:Cross-Attention分支通过时间嵌入增强双时相特征的时间差异,CoordAtt分支则强化局部结构细节。实验表明,STSAM能显著提升变化检测性能,同时保持训练稳定性。文章详细介绍了模块结构、原理、优势,并提供了完整的核心代码实现和配置方法,包括三种改进方案。 阅读详情

相关推荐

Anaconda/Miniconda的删除和安装

要在 MacBook 上删除 Anaconda 或 Miniconda,并重新安装它,您可以按照以下步骤进行操作。

qq_27390023的博客 3042

mysql读取数据库的结果ResultSet反射生成对象的方法

1.读取数据库 public List<T_Einteractive_Question> getEinteractiveQuestions(Connection conn){ ResultSet rs = null; List<T_Einteractive> result = new ArrayList<T_Einteractive>(); try { String sql = "select * from T_Einteractive";

寒夜二十五 505

变压器铁心100Hz振动噪声的COMSOL磁致伸缩仿真全流程

磁致伸缩是铁磁材料在磁场作用下发生尺寸变化的现象,也是变压器铁心振动与噪声产生的根本原因。由于应变与磁通密度近似成平方关系,50Hz电网激励下铁心振动基频为100Hz。借助COMSOL多物理场仿真,可将磁场计算结果映射为结构应力和变形,完成“电磁—结构”单向耦合分析。该技术广泛应用于变压器振动噪声预测、结构优化及故障诊断等工程场景。本文从磁致伸缩物理机理出发,系统梳理了材料参数、等效建模、边界条件设置和结果校核等关键步骤,帮助工程师掌握从磁致伸缩到结构变形的完整仿真链路,解决实际工程对标难题。

weixin_33796177的博客 325

将jdbc结果集ResultSet转换成对象列表

将jdbc结果集转换成对象列表  估计hibernate就是用得这种方式进行转换的。  实体对象  点击(此处)折叠或打开 package test; //实体对象,该对象的属性与数据库中的字段相同,当然可以改变具体看需求 public class Person {     private int id;     private in

奔跑的蜗牛 1万+

基于Transformer和图卷积网络的时空人体运动预测网络

本文主要介绍了基于Transformer和图卷积网络的时空人体运动预测网络。首先,文章详细阐述了Transformer模型的原理和优点,指出其通过自注意力机制实现序列数据的建模和处理,能够捕捉长距离依赖关系。然后,文章介绍了图卷积网络的基本概念和应用场景,强调其通过邻居节点信息聚合实现空间特征的提取和融合。接着,文章详细设计了时空人体运动预测网络的总体架构,包括基于Transformer的时间特征提取模块、基于图卷积的空间特征融合模块以及时空特征联合预测模块。

babyai996的博客 1489

PCIe 6.0实战指南:从链路训练到信号完整性的避坑手册

本文是一份针对PCIe 6.0硬件工程师的实战避坑指南。文章深入解析了从NRZ到PAM4调制带来的信号完整性挑战,详细拆解了链路训练(LTSSM)的复杂过程与调试方法,并提供了从信道仿真到实验室实测(如使用Keysight示波器进行眼图与误码率分析)的完整信号完整性闭环验证策略,帮助工程师解决高速率下的链路不稳定与降速问题。

weixin_29306875的博客 352

Mybatis学习

mybatis是一款半自动化的ORM框架 ,之所以说半自动,是因为使用mybatis时,需要手动写SQL语句,不像全自动的hibernate,只需要做好对象和数据库字段的映射关系,就可以CRUD操作。由于Mybatis支持解析SQL语句,所以相较于hibernate,灵活性大大增强。 ...

jdk819的博客 575

gtsam官方文档: The new IMU Factor学习笔记

gtsam官方文档:The new IMU Factor 本文为gtsam imu预积分文档学习笔记,为gtsam基于切向量实现的imu预积分的理论基础。 导航状态 定义导航状态为 Xbn={Rbn,Pbn,Vbn}X^n_b=\{R^n_b,P^n_b,V^n_b\}Xbn​={Rbn​,Pbn​,Vbn​} 上角标n:导航(navigation)坐标系 下角标b:载体(body)坐标系 下文均省略上下标 矢量场与微分方程 对于导航问题我们用如下微分方程描述 X˙(t)=F(t,X)\dot X(t)

南柯一梦的博客 1616

Java实现数据库ResultSet的数据转换为Object对象

使用原因 我们在进行数据库查询的时候,查询出来的结果是ResultSet对象,我们需要一行一行的遍历,用Object.setXxxx(ressultSet.getString(“xxx”))。如果表的字段比较多的话,每次查询都这样写工作量就很多拉,无疑是浪费时间和精力。 解决思路 我们可以让查询的RestultSet对象一行数据和数据库表对象的实体类Object一起传入一个类中进行“加工”,把Re...

youth_shouting的博客 5254

STM32HAL库 基于外部Flash+FatFs模拟U盘方式进行固件拷贝升级(详解)

STM32HAL库 基于外部Flash+FatFs模拟U盘方式进行固件拷贝升级

qq_36075612的博客 1万+

CODESYS做Modbus TCP主站踩坑记:从IP配置到数据映射的完整避坑指南

本文详细记录了在CODESYS中配置Modbus TCP主站的全过程,从IP配置到数据映射的常见问题及解决方案。重点解析了网络适配器选择、Slave ID误解、地址偏移陷阱等关键问题,并提供了实用的调试技巧和性能优化建议,帮助工业通信开发者高效避坑。

weixin_30642561的博客 635

29、通过反射完成resultSet到Object的转换

学习目标: 1、巩固反射、泛型等知识的使用 2、编写高级BaseDao类 学习过程: 有关JDBC的内容就讲到这里,下面我们对BaseDao进一步封装,主要应用一下以前学习的泛型和反射的概念。毕竟大家对java高级方面的内容掌握的并不是很好。 首先我们先看看在所有的查询语句中都需要把结果集的内容转换成为对象如下面的这段代码:  while (rs.next()) {     // ...

JavaDayUp 1354

CSP-J2019普及组复赛T4:加工零件

CSP-J2020普及组复赛T1:优秀的拆分,广度优先遍历求最短路。

少儿编程乔老师 1860

MyBatis的工作原理

MyBatis 是一个功能强大的持久层框架,通过对 SQL 语句的精确控制和方便的映射配置,提供了一种灵活且高效的数据库访问方式。MyBatis 的工作原理主要围绕SqlSessionMapperExecutor这几个核心组件展开,通过配置文件和映射文件,将 Java 对象和数据库表有效地连接起来。MyBatis 通过动态代理、缓存机制、动态 SQL、插件机制等特性,极大地提升了数据库操作的简洁性和可维护性,同时保留了对 SQL 语句的完全控制权,适合于各种需要精细化控制 SQL 的场景。

Flying_Fish_roe的博客 3211

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

MyBatis基本工作原理介绍

1、MyBatis基本工作原理介绍 计算机的基本工作就是存储和计算,而MyBatis是存储领域的利器。MyBatis的基本工作原理就是:先封装SQL,接着调用JDBC操作数据库,最后把数据库返回的表结果封装成Java类。 2、MyBatis的核心流程介绍 mybatis应用程序通过SqlSessionFactoryBuilder从mybatis-config.xml配置文件中构建出SqlSessionFactory,然后,SqlSessionFactory的实例直接开启一个SqlSession,再通过

weixin_44431073的博客 2万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Mybatis 的工作原理及流程

MyBatis的底层操作封装了JDBC的API,MyBatis的工作原理以及核心流程与JDBC的使用步骤一脉相承,MyBatis的核心对象(SqlSession,Executor)与JDBC的核心对象(Connection,Statement)相互对应。本文的核心观点是:从JDBC入手并立足于JDBC,才能深入的理解MyBatis的工作原理以及核心流程。

qq_52252193的博客 3555

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

MyBatis 的工作原理解析

本文记录 Mybatis 的工作原理解析,做到知识梳理总结的作用。

m0_49692893的博客 3603

说说mybatis的工作原理

MyBatis 会解析 SQL 映射文件,执行对应的 SQL 语句,并将结果映射到 Java 对象。你需要创建一个 Java 接口,接口中声明了数据库操作的方法,然后创建对应的 XML 映射文件,将 SQL 语句与接口方法进行关联。它的优点之一是提供了灵活的 SQL 映射和参数处理方式,使得开发人员可以更好地控制 SQL 语句和 Java 对象之间的映射关系。MyBatis 是一个持久层框架,它的工作原理涉及到配置文件、SQL 映射文件、Java 对象和数据库的交互。这是一个典型的 SQL 注入攻击。

tanwu1的博客 172

了解Mybatis的工作原理吗

来源:cnblogs.com/scuury/p/10371246.html 推荐阅读 1.SpringBoot 整合篇 2.手写一套迷你版HTTP服务器 3.记住:永远不要在MySQL中使用UTF-8 4.Springboot启动原理解析 近来想写一个mybatis的分页插件,但是在写插件之前肯定要了解一下mybatis具体的工作原理吧,于是边参考别人的博客,边看源码就开干了。...

Java笔记虾 1243

Mybatis的工作原理

1、工作原理 读取 MyBatis 配置文件:mybatis-config.xml 为 MyBatis 的全局配置文件,配置了 MyBatis 的运行环境等信息,例如数据库连接信息。 **加载映射文件。**映射文件即 SQL 映射文件,该文件中配置了操作数据库的 SQL 语句,需要在 MyBatis 配置文件 mybatis-config.xml 中加载。mybatis-config.xml 文件可以加载多个映射文件,每个文件对应数据库中的一张表。 **构造会话工厂:**通过 MyBatis 的环境..

Mark 9768

MyBatis的工作原理和应用实例

MyBatis 是一个优秀的持久层框架,它封装了 JDBC 的底层操作,MyBatis 通过其灵活的配置和强大的映射能力,大大简化了数据库操作,同时保留了 SQL 的灵活性和可控性,是 Java 项目中常用的持久层解决方案。

weixin_46455584的博客 1242

能说说MyBatis的工作原理吗?

能说说MyBatis的工作原理吗?

java1234的博客 1613

详解关于mybatis工作原理以及优缺点

(3)基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。‌3️⃣简化JDBC操作‌:MyBatis封装了大部分JDBC代码,减少了设置参数、获取结果集等重复性工作,简化了异常处理,减少了潜在的内存泄漏风险‌。‌2️⃣高性能‌:MyBatis提供了高效的缓存机制,能够减少数据库操作的次数,支持批量操作和分页查询等功能,从而提高应用程序的性能‌。2. 然后,MyBatis将SQL语句对象与用户提供的参数绑定,生成完整的SQL语句。

-天涯76的个人博客 626

MyBatis工作原理

MyBatis是一个轻量级的数据持久化框架,通过XML/注解配置简化JDBC操作。核心组件包括:1)配置加载(mybatis-config.xml)定义数据库连接;2)映射器(Mapper)接口与XML文件绑定SQL语句;3)SqlSessionFactory构建会话工厂;4)SqlSession执行SQL并处理结果映射。其工作流程为:解析配置→创建会话→执行映射SQL→结果转换。支持动态SQL和两级缓存,既保持SQL灵活性又减少样板代码,通过与Spring集成实现线程安全的事务管理。相比全自动ORM框架,

SHGXO183的博客 1344

【mybatis原理工作原理】

文章目录mybatis原理: mybatis原理: mybatis的工作原理就是:先封装sql,接着调用jdbc操作数据库,最后把数据库返回的表结果封装成java类。 通过代码实现jdbc查询操作: mybatis-config.xml类 <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://myba

qq_33700648的博客 1445

mysql之MyBatis核心工作原理

接下来我们就开始MyBatis的源码之旅,首先大家要从宏观上了解Mybatis的整体框架分为三层,分别是基础支持层、核心处理层、和接口层。如下图然后根据前面讲解的MyBatis的应用案例,给出MyBatis的主要工作流程图在MyBatis的主要工作流程里面,不同的功能是由很多不同的类协作完成的,它们分布在MyBatis jar包的不同的package里面。大概有一千多个类,这样看起来不够清楚,不知道什么类在什么环节工作,属于什么层次。

励志成为一名优秀的全能型软件开发工程师。 1726
上一篇: LayUI富文本域使用案例
下一篇: python操作mysql
普通网友
博客等级 码龄3年 1923粉丝 116原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值