导航:首页 > 源码编译 > ybatis源码阅读

ybatis源码阅读

发布时间:2022-07-22 03:57:41

Ⅰ 《深入浅出MyBatis技术原理与实战》pdf下载在线阅读全文,求百度网盘云资源

《深入浅出MyBatis技术原理与实战》网络网盘pdf最新全集下载:
链接:https://pan..com/s/1LxgP-ibmyXjclY23yXMN-Q

?pwd=gijo 提取码:gijo
简介:随着大数据时代的到来,java持久层框架MyBatis已经成为越来越多企业的选择。遗憾的是,时至今日国内依然没有一本讨论MyBatis的书,这增加了初学者的学习难度,初学者往往只能基于零星的案例来学习MyBatis,无法系统地掌握MyBatis,更不用说精通了。《深入浅出MyBatis技术原理与实战》是笔者通过大量实践和研究源码后创作而成的,是国内第一本系统介绍MyBatis的着作本书分为3个部分,依次介绍了MyBatis的基础应用、原理及插件开发、实践应用,使读者能够由法入深、循序渐进地掌握MyBatis技术。首先,本书在官方API的基础上完善了许多重要的论述和实例,并且给出了实操建议,帮助读者正确掌握MyBatis。其次,本书详细讲述了MyBatis的内部运行原理,并全面讨论了插件的开发。最后,本着学以致用的原则,笔者阐述了MyBatis-Spring项目和一些MyBatis开发常见的实例,使读者能够学得会,用得好。

Ⅱ 配置sqlsessiontemplate有什么用

工作中,需要学习一下MyBatis sqlSession的产生过程,翻看了mybatis-spring的源码,阅读了一些mybatis的相关doc,对mybatis sqlSession有了一些认知和理解,这里简单的总结和整理一下。

首先, 通过翻阅源码,我们来整理一下mybatis进行持久化操作时重要的几个类:
SqlSessionFactoryBuilder:build方法创建SqlSessionFactory实例。
SqlSessionFactory:创建SqlSession实例的工厂。

SqlSession:用于执行持久化操作的对象,类似于jdbc中的Connection。
SqlSessionTemplate:MyBatis提供的持久层访问模板化的工具,线程安全,可通过构造参数或依赖注入SqlSessionFactory实例。

Hibernate是与MyBatis类似的orm框架,这里与Hibernate进行一下对比,Hibernate中对于connection的管理,是通过以下几个重要的类:
SessionFactory:创建Session实例的工厂,类似于MyBatis中的SqlSessionFactory。
Session:用来执行持久化操作的对象,类似于jdbc中的Connection。

HibernateTemplate:Hibernate提供的持久层访问模板化的工具,线程安全,可通过构造参数或依赖注入SessionFactory实例。

在日常的开发中,我们经常需要这样对MyBatis和Spring进行集成,把sqlSessionFactory交给Spring管理,通常情况下,我们这样配置:
?

1
2
3

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>

通过上面的配置,Spring将自动创建一个SqlSessionFactory对象,其中使用到了org.mybatis.spring.SqlSessionFactoryBean,其 是MyBatis为Spring提供的用于创建SqlSessionFactory的类,将在Spring应用程序的上下文建议一下可共享的 MyBatis SqlSessionFactory实例,我们可以通过依赖注入将SqlSessionFactory传递给MyBatis的一些接口。

如果通过Spring进行事务的管理,我们需要增加Spring注解的事务管理机制,如下配置:
?

1
2
3
4
5

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<tx:annotation-driven/>

这样,我们就可以使用Spring @Transactional注解,进行事务的控制,表明所注释的方法应该在一个事务中运行。 Spring将在事务成功完成后提交事务,在事务发生错误时进行异常回滚,而且,Spring会将产生的MyBatis异常转换成适当的 DataAccessExceptions,从而提供具体的异常信息。

下面,我们通过分析SqlSessionUtils中getSession的源码,来详细的了解一下sqlSession的产生过程,源码如下:
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, exceptionTranslator) {

notNull(sessionFactory, "No SqlSessionFactory specified");
notNull(executorType, "No ExecutorType specified");

SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);

if (holder != null && holder.isSynchronizedWithTransaction()) {
if (holder.getExecutorType() != executorType) {
throw new ("Cannot change the ExecutorType when there is an existing transaction");
}

holder.requested();

if (logger.isDebugEnabled()) {
logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
}

return holder.getSqlSession();
}

if (logger.isDebugEnabled()) {
logger.debug("Creating a new SqlSession");
}

SqlSession session = sessionFactory.openSession(executorType);

// Register session holder if synchronization is active (i.e. a Spring TX is active)
//
// Note: The DataSource used by the Environment should be synchronized with the
// transaction either through DataSourceTxMgr or another tx synchronization.
// Further assume that if an exception is thrown, whatever started the transaction will
// handle closing / rolling back the Connection associated with the SqlSession.
if (isSynchronizationActive()) {
Environment environment = sessionFactory.getConfiguration().getEnvironment();

if (environment.getTransactionFactory() instanceof ) {
if (logger.isDebugEnabled()) {
logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
}

holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
bindResource(sessionFactory, holder);
registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
holder.(true);
holder.requested();
} else {
if (getResource(environment.getDataSource()) == null) {
if (logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because DataSource is not transactional");
}
} else {
throw new (
"SqlSessionFactory must be using a in order to use Spring transaction synchronization");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active");
}
}

return session;
}

上面的getSession方法,会从Spring的事务管理器中获取一个SqlSession或创建一个新的SqlSession,将试图从当前事务中得到一个SqlSession,然后,如果配置有事务管理器的工厂并且Spring 的事务管理器是活跃的,它将会锁定当前事务的SqlSession,保证同步。主要是通过以下几个步骤进行SqlSession的创建:
它会首先获取SqlSessionHolder,SqlSessionHolder用于在中保持当前的SqlSession。
如果holder不为空,并且holder被事务锁定,则可以通过holder.getSqlSession()方法,从当前事务中获取sqlSession,即 Fetched SqlSession from current transaction。

如果不存在holder或没有被事务锁定,则会创建新的sqlSession,即 Creating a new SqlSession,通过sessionFactory.openSession()方法。

如果当前线程的事务是活跃的,将会为SqlSession注册事务同步,即 Registering transaction synchronization for SqlSession。

Ⅲ mybatis工作原理及为什么要用

一、mybatis的工作原理:

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。

MyBatis使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Ordinary Java Objects,普通的 Java对象)映射成数据库中的记录。

每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。用xml文件构建SqlSessionFactory实例是非常简单的事情。

推荐在这个配置中使用类路径资源,但可以使用任何Reader实例,包括用文件路径或file://开头的url创建的实例。MyBatis有一个实用类----Resources,它有很多方法,可以方便地从类路径及其它位置加载资源。

二、使用mybatis的原因:因为mybatis具有许多的优点,具体如下:

1、简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。

2、灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。

3、解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。

4、提供映射标签,支持对象与数据库的orm字段关系映射。

5、提供对象关系映射标签,支持对象关系组建维护。

6、提供xml标签,支持编写动态sql。

(3)ybatis源码阅读扩展阅读:

mybatis的功能构架:

1、API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。

2、数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。

3、基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。

Ⅳ 如何在mybatis中调试查看生成的sql语句

mybatis的源码中查看生成的sql语句,参考执行以下代码即可。具体代码如下:把里面PooledDataSource类的log输出部分,换成log.warn之后,重新打jar包,放到项目中,日志级别改为info,如:log4j.rootLogger=info,stdout,Rlog4j.appender.std

Ⅳ 如何去阅读并学习一些优秀的开源框架的源码 来自

没有目标的去看所谓的源码,没有任何的意义。
最适合看源码的就是,你对完成一个功能感兴趣,所以你想要了解他。
比如说Mybatis,你想了解他的代码生成机制,自己先去思考,如果是你做,该怎么做,再去看源码。
再比如说Log4j.打日志的时候是异步的吗?如果我需要把日志打到另外一台机器上,我该怎么做?
带着这些问题去思考解决方案。
那么天底下的源码都是你的老师。
千万别东一锤子西一锤子的去瞎看。

Ⅵ 怎么学习mybatis框架的源码

刚刚好我前段时间做了一个基于SpringMVC + Mybatis + Redis + Freemarker(JSP)的权限控制Demo。地址看下面代码:/** * 网络不让输入网址 * 地址为 */String url = "

Ⅶ 哪一个框架的源码适合拿来阅读学习

不要看框架源码,最好先打好基础,比如反射,代理等。因为很多框架的功能已经十分繁多,光是功能(英文)你都难以弄懂,更何况是参合了很多中间变量、逻辑功能的源码,越看越难以理解。即使要学习框架,也要先从javadoc注释,即API帮助文档开始,了解数据流的流入和流出。用源码反向猜测设计逻辑是吃力不讨好的事,一没完整注释,二不是本人,三反射的应用最伤脑细胞,你压根不知道在哪里被插了一脚。如果框架适合用来学习,那么改别人的代码也就不是个事了。问题来了,为何程序员都不喜欢改别人的代码bug?

Ⅷ 如何学习hibernate源码

我来分享一下查看源码的方法:

查看源码的首要任务是要有一款上手的工具,这里用的是 IDEA。IDEA 的功能比较强大,包括 查看类结构图,debug。这两个是查看源码的关键功能。

查看源码可以静态查看和动态查看,静态查看的方法是查看类图,还有 ALT + f7 查看方法在哪里被调用或者类在哪里被调用。在看 spring 源码的时候就是用这种方法,不过这种方法对阅读者的要求比较高,包括要了解这个方法的执行,设计模式的理解,以及框架是如何配置这个类的。第二种方法是 debug。debug 方法是后来才发现的一个重要的 查看源码的方法,要点是掌握执行栈,就能掌握整个执行流程。比如这个是在debug hibernate 源码的时候的截图,可以看到这个执行栈非常深,从 spring-data-jpa 到 hibernate 中间经过好几层的代理,主要完成一些适配,事务,拦截器等等操作,然后再到 hibernate 核心代码,最后就是 jdbc 的 statement。方法栈中的每一个方法都是可以查看的,里面的变量有时候是代理了好几层,所以要 F7 进去才能看到真正的执行类。

上面是简单的简述 mybatis 的 cache 机制的源码,真正想让读者明白的是,debug 如何查看源码,查看源码需要抓住一个主题,不然在阅读庞大的框架的时候会找不着北。

所以,阅读源码需要掌握工具使用,debug, 查看类图,查看方法在哪里调用,软知识是要掌握设计模式,对框架的概念有了解。

Ⅸ 初看Mybatis 源码 SQL是怎么执行的

一条sql语句到底是怎么执行的?我们知道Mybatis其实是对JDBC的一个封装。假如我执行
session.update("com.mybatis..AuthUserDao.updateAuthUserEmailByName", [email protected]);
语句,追踪下来,Executor、 BaseStatementHandler等等。在 SimpleExecutor 中有如下代码:
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.update(stmt);
} finally {
closeStatement(stmt);
}
}
1. 首先获取相关配置信息,这个在初始化时,从配置文件中解析而来
2. 新建了一个handler
3. 做了执行statement之前的准备工作。看看准备了些什么,跟踪代码,最后进入了DataSource类的doGetConnection方法,该方法做如下操作:
private Connection doGetConnection(Properties properties) throws SQLException {
initializeDriver();
Connection connection = DriverManager.getConnection(url, properties);
configureConnection(connection);
return connection;
}

private synchronized void initializeDriver() throws SQLException {
if (!registeredDrivers.containsKey(driver)) {
Class<?> driverType;
try {
if (driverClassLoader != null) {
driverType = Class.forName(driver, true, driverClassLoader);
} else {
driverType = Resources.classForName(driver);
}
// DriverManager requires the driver to be loaded via the system ClassLoader.
// http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
Driver driverInstance = (Driver)driverType.newInstance();
DriverManager.registerDriver(new DriverProxy(driverInstance));
registeredDrivers.put(driver, driverInstance);

Ⅹ 怎么没有mybatis源码解析相关的文档

我们还记得是这样配置sqlSessionFactory的:
[java] view plain
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:configuration.xml"></property>
<property name="mapperLocations" value="classpath:com/xxx/mybatis/mapper/*.xml"/>
<property name="typeAliasesPackage" value="com.tiantian.mybatis.model" />
</bean>
这里配置了一个mapperLocations属性,它是一个表达式,sqlSessionFactory会根据这个表达式读取包com.xxx.myts.mapper下面的所有xml格式文件,那么具体是怎么根据这个属性来读取配置文件的呢?
答案就在SqlSessionFactoryBean类中的buildSqlSessionFactory方法中:

[java] view plain
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 + "'");
}
}
}

mybatis使用XMLMapperBuilder类的实例来解析mapper配置文件。
[java] view plain
public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()),
configuration, resource, sqlFragments);
}

[java] view plain
private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
super(configuration);
this.builderAssistant = new MapperBuilderAssistant(configuration, resource);
this.parser = parser;
this.sqlFragments = sqlFragments;
this.resource = resource;
}
接着系统调用xmlMapperBuilder的parse方法解析mapper。

[java] view plain
public void parse() {
//如果configuration对象还没加载xml配置文件(避免重复加载,实际上是确认是否解析了mapper节点的属性及内容,
//为解析它的子节点如cache、sql、select、resultMap、parameterMap等做准备),
//则从输入流中解析mapper节点,然后再将resource的状态置为已加载
if (!configuration.isResourceLoaded(resource)) {
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
bindMapperForNamespace();
}
//解析在configurationElement函数中处理resultMap时其extends属性指向的父对象还没被处理的<resultMap>节点
parsePendingResultMaps();
//解析在configurationElement函数中处理cache-ref时其指向的对象不存在的<cache>节点(如果cache-ref先于其指向的cache节点加载就会出现这种情况)
parsePendingChacheRefs();
//同上,如果cache没加载的话处理statement时也会抛出异常
parsePendingStatements();
}

mybatis解析mapper的xml文件的过程已经很明显了,接下来我们看看它是怎么解析mapper的:
[java] view plain
private void configurationElement(XNode context) {
try {
//获取mapper节点的namespace属性
String namespace = context.getStringAttribute("namespace");
if (namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
//设置当前namespace
builderAssistant.setCurrentNamespace(namespace);
//解析mapper的<cache-ref>节点
cacheRefElement(context.evalNode("cache-ref"));
//解析mapper的<cache>节点
cacheElement(context.evalNode("cache"));
//解析mapper的<parameterMap>节点
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
//解析mapper的<resultMap>节点
resultMapElements(context.evalNodes("/mapper/resultMap"));
//解析mapper的<sql>节点
sqlElement(context.evalNodes("/mapper/sql"));
//使用XMLStatementBuilder的对象解析mapper的<select>、<insert>、<update>、<delete>节点,
//myts会使用MappedStatement.Builder类build一个MappedStatement对象,
//所以myts中一个sql对应一个MappedStatement
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
}
}
configurationElement函数几乎解析了mapper节点下所有子节点,至此myts解析了mapper中的所有节点,并将其加入到了Configuration对象中提供给sqlSessionFactory对象随时使用。这里我们需要补充讲一下myts是怎么使用XMLStatementBuilder类的对象的parseStatementNode函数借用MapperBuilderAssistant类对象builderAssistant的addMappedStatement解析MappedStatement并将其关联到Configuration类对象的:

[java] view plain
public void parseStatementNode() {
//ID属性
String id = context.getStringAttribute("id");
//databaseId属性
String databaseId = context.getStringAttribute("databaseId");

if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
//fetchSize属性
Integer fetchSize = context.getIntAttribute("fetchSize");
//timeout属性
Integer timeout = context.getIntAttribute("timeout");
//parameterMap属性
String parameterMap = context.getStringAttribute("parameterMap");
//parameterType属性
String parameterType = context.getStringAttribute("parameterType");
Class<?> parameterTypeClass = resolveClass(parameterType);
//resultMap属性
String resultMap = context.getStringAttribute("resultMap");
//resultType属性
String resultType = context.getStringAttribute("resultType");
//lang属性
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);

Class<?> resultTypeClass = resolveClass(resultType);
//resultSetType属性
String resultSetType = context.getStringAttribute("resultSetType");
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
//是否是<select>节点
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
//flushCache属性
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
//useCache属性
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
//resultOrdered属性
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());

// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);

// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
//resultSets属性
String resultSets = context.getStringAttribute("resultSets");
//keyProperty属性
String keyProperty = context.getStringAttribute("keyProperty");
//keyColumn属性
String keyColumn = context.getStringAttribute("keyColumn");
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
//useGeneratedKeys属性
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? new Jdbc3KeyGenerator() : new NoKeyGenerator();
}

builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
由以上代码可以看出myts使用XPath解析mapper的配置文件后将其中的resultMap、parameterMap、cache、statement等节点使用关联的builder创建并将得到的对象关联到configuration对象中,而这个configuration对象可以从sqlSession中获取的,这就解释了我们在使用sqlSession对数据库进行操作时myts怎么获取到mapper并执行其中的sql语句的问题。

阅读全文

与ybatis源码阅读相关的资料

热点内容
扫地机怎么安装app 浏览:317
考研结合特征值计算法 浏览:514
操作系统算法综合题 浏览:150
华为程序员待遇 浏览:545
程序员带娃的图片 浏览:77
迷你云服务器怎么下载 浏览:813
福州溯源码即食燕窝 浏览:232
当乐服务器怎么样 浏览:713
nc编程软件下载 浏览:382
如何限制手机app的使用 浏览:307
安卓华为手机怎么恢复桌面图标 浏览:956
我的世界电脑版服务器地址在哪找 浏览:533
违抗了命令 浏览:256
安卓如何实现拖拽放置 浏览:91
净资产收益率选股指标源码 浏览:599
血压力传感器计算公式单片机 浏览:466
全网接口vip影视解析源码 浏览:916
如何破解服务器远程密码错误 浏览:377
平安深圳app如何实名认证 浏览:500
linux网络监控软件 浏览:889