如何看mybatis源码_怎么看mybatis源码

hacker|
102

文章目录:

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

如果你在vmware下编译内核,硬盘用的是scsi的,以下三个选项必选:

Device Drivers ---*SCSI device support (此项不选的话,下面两项就选择不上)

Device Drivers ---*SCSI device support ---*SCSI disk support

Device Drivers---8SCSI device support---SCSI low-level drivers---*; BusLogic SCSI support

Mybatis里面的TypeHandler是做什么的

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时,都会用类型处理器将获取的值以合适的方式转换成 Java 类型。Mybatis默认为我们实现了许多TypeHandler, 当我们没有配置指定TypeHandler时,Mybatis会根据参数或者返回结果的不同,默认为我们选择合适的TypeHandler处理。

那么,Mybatis为我们实现了哪些TypeHandler呢? 我们怎么自定义实现一个TypeHandler ? 这些都会在接下来的mybatis的源码中看到。

在看源码之前,还是像之前一样,先看看怎么配置吧?

配置TypeHandler:

configuration

typeHandlers

!--

当配置package的时候,mybatis会去配置的package扫描TypeHandler

package name="com.dy.demo"/

--

!-- handler属性直接配置我们要指定的TypeHandler --

typeHandler handler=""/

!-- javaType 配置java类型,例如String, 如果配上javaType, 那么指定的typeHandler就只作用于指定的类型 --

typeHandler javaType="" handler=""/

!-- jdbcType 配置数据库基本数据类型,例如varchar, 如果配上jdbcType, 那么指定的typeHandler就只作用于指定的类型 --

typeHandler jdbcType="" handler=""/

!-- 也可两者都配置 --

typeHandler javaType="" jdbcType="" handler=""/

/typeHandlers

......

/configuration

上面简单介绍了一下TypeHandler, 下面就看看mybatis中TypeHandler的源码了。

=========================================================我是源码分割线==========================================================

老规矩,先从对xml的解析讲起:

/**

* 解析typeHandlers节点

*/

private void typeHandlerElement(XNode parent) throws Exception {

if (parent != null) {

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

//子节点为package时,获取其name属性的值,然后自动扫描package下的自定义typeHandler

if ("package".equals(child.getName())) {

String typeHandlerPackage = child.getStringAttribute("name");

typeHandlerRegistry.register(typeHandlerPackage);

} else {

//子节点为typeHandler时, 可以指定javaType属性, 也可以指定jdbcType, 也可两者都指定

//javaType 是指定java类型

//jdbcType 是指定jdbc类型(数据库类型: 如varchar)

String javaTypeName = child.getStringAttribute("javaType");

String jdbcTypeName = child.getStringAttribute("jdbcType");

//handler就是我们配置的typeHandler

String handlerTypeName = child.getStringAttribute("handler");

//resolveClass方法就是我们上篇文章所讲的TypeAliasRegistry里面处理别名的方法

Class? javaTypeClass = resolveClass(javaTypeName);

//JdbcType是一个枚举类型,resolveJdbcType方法是在获取枚举类型的值

JdbcType jdbcType = resolveJdbcType(jdbcTypeName);

Class? typeHandlerClass = resolveClass(handlerTypeName);

//注册typeHandler, typeHandler通过TypeHandlerRegistry这个类管理

if (javaTypeClass != null) {

if (jdbcType == null) {

typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);

} else {

typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);

}

} else {

typeHandlerRegistry.register(typeHandlerClass);

}

}

}

}

}

接下来看看TypeHandler的管理注册类:

TypeHandlerRegistry:

/**

* typeHandler注册管理类

*/

public final class TypeHandlerRegistry {

//源码一上来,二话不说,几个大大的HashMap就出现,这不又跟上次讲的typeAliases的注册类似么

//基本数据类型与其包装类

private static final MapClass?, Class? reversePrimitiveMap = new HashMapClass?, Class?() {

private static final long serialVersionUID = 1L;

{

put(Byte.class, byte.class);

put(Short.class, short.class);

put(Integer.class, int.class);

put(Long.class, long.class);

put(Float.class, float.class);

put(Double.class, double.class);

put(Boolean.class, boolean.class);

put(Character.class, char.class);

}

};

//这几个MAP不用说就知道存的是什么东西吧,命名的好处

private final MapJdbcType, TypeHandler? JDBC_TYPE_HANDLER_MAP = new EnumMapJdbcType, TypeHandler?(JdbcType.class);

private final MapType, MapJdbcType, TypeHandler? TYPE_HANDLER_MAP = new HashMapType, MapJdbcType, TypeHandler?();

private final TypeHandlerObject UNKNOWN_TYPE_HANDLER = new UnknownTypeHandler(this);

private final MapClass?, TypeHandler? ALL_TYPE_HANDLERS_MAP = new HashMapClass?, TypeHandler?();

//就像上篇文章讲的typeAliases一样,mybatis也默认给我们注册了不少的typeHandler

//具体如下

public TypeHandlerRegistry() {

register(Boolean.class, new BooleanTypeHandler());

register(boolean.class, new BooleanTypeHandler());

register(JdbcType.BOOLEAN, new BooleanTypeHandler());

register(JdbcType.BIT, new BooleanTypeHandler());

register(Byte.class, new ByteTypeHandler());

register(byte.class, new ByteTypeHandler());

register(JdbcType.TINYINT, new ByteTypeHandler());

register(Short.class, new ShortTypeHandler());

register(short.class, new ShortTypeHandler());

register(JdbcType.SMALLINT, new ShortTypeHandler());

register(Integer.class, new IntegerTypeHandler());

register(int.class, new IntegerTypeHandler());

register(JdbcType.INTEGER, new IntegerTypeHandler());

register(Long.class, new LongTypeHandler());

register(long.class, new LongTypeHandler());

register(Float.class, new FloatTypeHandler());

register(float.class, new FloatTypeHandler());

register(JdbcType.FLOAT, new FloatTypeHandler());

register(Double.class, new DoubleTypeHandler());

register(double.class, new DoubleTypeHandler());

register(JdbcType.DOUBLE, new DoubleTypeHandler());

register(String.class, new StringTypeHandler());

register(String.class, JdbcType.CHAR, new StringTypeHandler());

register(String.class, JdbcType.CLOB, new ClobTypeHandler());

register(String.class, JdbcType.VARCHAR, new StringTypeHandler());

register(String.class, JdbcType.LONGVARCHAR, new ClobTypeHandler());

register(String.class, JdbcType.NVARCHAR, new NStringTypeHandler());

register(String.class, JdbcType.NCHAR, new NStringTypeHandler());

register(String.class, JdbcType.NCLOB, new NClobTypeHandler());

register(JdbcType.CHAR, new StringTypeHandler());

register(JdbcType.VARCHAR, new StringTypeHandler());

register(JdbcType.CLOB, new ClobTypeHandler());

register(JdbcType.LONGVARCHAR, new ClobTypeHandler());

register(JdbcType.NVARCHAR, new NStringTypeHandler());

register(JdbcType.NCHAR, new NStringTypeHandler());

register(JdbcType.NCLOB, new NClobTypeHandler());

register(Object.class, JdbcType.ARRAY, new ArrayTypeHandler());

register(JdbcType.ARRAY, new ArrayTypeHandler());

register(BigInteger.class, new BigIntegerTypeHandler());

register(JdbcType.BIGINT, new LongTypeHandler());

register(BigDecimal.class, new BigDecimalTypeHandler());

register(JdbcType.REAL, new BigDecimalTypeHandler());

register(JdbcType.DECIMAL, new BigDecimalTypeHandler());

register(JdbcType.NUMERIC, new BigDecimalTypeHandler());

register(Byte[].class, new ByteObjectArrayTypeHandler());

register(Byte[].class, JdbcType.BLOB, new BlobByteObjectArrayTypeHandler());

register(Byte[].class, JdbcType.LONGVARBINARY, new BlobByteObjectArrayTypeHandler());

register(byte[].class, new ByteArrayTypeHandler());

register(byte[].class, JdbcType.BLOB, new BlobTypeHandler());

register(byte[].class, JdbcType.LONGVARBINARY, new BlobTypeHandler());

register(JdbcType.LONGVARBINARY, new BlobTypeHandler());

register(JdbcType.BLOB, new BlobTypeHandler());

register(Object.class, UNKNOWN_TYPE_HANDLER);

register(Object.class, JdbcType.OTHER, UNKNOWN_TYPE_HANDLER);

register(JdbcType.OTHER, UNKNOWN_TYPE_HANDLER);

register(Date.class, new DateTypeHandler());

register(Date.class, JdbcType.DATE, new DateOnlyTypeHandler());

register(Date.class, JdbcType.TIME, new TimeOnlyTypeHandler());

register(JdbcType.TIMESTAMP, new DateTypeHandler());

register(JdbcType.DATE, new DateOnlyTypeHandler());

register(JdbcType.TIME, new TimeOnlyTypeHandler());

register(java.sql.Date.class, new SqlDateTypeHandler());

register(java.sql.Time.class, new SqlTimeTypeHandler());

register(java.sql.Timestamp.class, new SqlTimestampTypeHandler());

// issue #273

register(Character.class, new CharacterTypeHandler());

register(char.class, new CharacterTypeHandler());

}

public boolean hasTypeHandler(Class? javaType) {

return hasTypeHandler(javaType, null);

}

public boolean hasTypeHandler(TypeReference? javaTypeReference) {

return hasTypeHandler(javaTypeReference, null);

}

public boolean hasTypeHandler(Class? javaType, JdbcType jdbcType) {

return javaType != null getTypeHandler((Type) javaType, jdbcType) != null;

}

public boolean hasTypeHandler(TypeReference? javaTypeReference, JdbcType jdbcType) {

return javaTypeReference != null getTypeHandler(javaTypeReference, jdbcType) != null;

}

public TypeHandler? getMappingTypeHandler(Class? extends TypeHandler? handlerType) {

return ALL_TYPE_HANDLERS_MAP.get(handlerType);

}

public T TypeHandlerT getTypeHandler(ClassT type) {

return getTypeHandler((Type) type, null);

}

public T TypeHandlerT getTypeHandler(TypeReferenceT javaTypeReference) {

return getTypeHandler(javaTypeReference, null);

}

public TypeHandler? getTypeHandler(JdbcType jdbcType) {

return JDBC_TYPE_HANDLER_MAP.get(jdbcType);

}

public T TypeHandlerT getTypeHandler(ClassT type, JdbcType jdbcType) {

return getTypeHandler((Type) type, jdbcType);

}

public T TypeHandlerT getTypeHandler(TypeReferenceT javaTypeReference, JdbcType jdbcType) {

return getTypeHandler(javaTypeReference.getRawType(), jdbcType);

}

private T TypeHandlerT getTypeHandler(Type type, JdbcType jdbcType) {

MapJdbcType, TypeHandler? jdbcHandlerMap = TYPE_HANDLER_MAP.get(type);

TypeHandler? handler = null;

if (jdbcHandlerMap != null) {

handler = jdbcHandlerMap.get(jdbcType);

if (handler == null) {

handler = jdbcHandlerMap.get(null);

}

}

if (handler == null type != null type instanceof Class Enum.class.isAssignableFrom((Class?) type)) {

handler = new EnumTypeHandler((Class?) type);

}

@SuppressWarnings("unchecked")

// type drives generics here

TypeHandlerT returned = (TypeHandlerT) handler;

return returned;

}

public TypeHandlerObject getUnknownTypeHandler() {

return UNKNOWN_TYPE_HANDLER;

}

public void register(JdbcType jdbcType, TypeHandler? handler) {

JDBC_TYPE_HANDLER_MAP.put(jdbcType, handler);

}

//

// REGISTER INSTANCE

//

怎么学习mybatis框架的源码

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

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

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

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

我们还记得是这样配置sqlSessionFactory的:

[java] view plain copy

bean id="sqlSessionFactory" class="5d94-e31d-d244-b849 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.mybaits.mapper下面的所有xml格式文件,那么具体是怎么根据这个属性来读取配置文件的呢?

答案就在SqlSessionFactoryBean类中的buildSqlSessionFactory方法中:

[java] view plain copy

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 copy

public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, MapString, XNode sqlFragments) {

this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()),

configuration, resource, sqlFragments);

}

[java] view plain copy

private XMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, MapString, 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 copy

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 copy

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节点,

//mybaits会使用MappedStatement.Builder类build一个MappedStatement对象,

//所以mybaits中一个sql对应一个MappedStatement

buildStatementFromContext(context.evalNodes("select|insert|update|delete"));

} catch (Exception e) {

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

}

}

configurationElement函数几乎解析了mapper节点下所有子节点,至此mybaits解析了mapper中的所有节点,并将其加入到了Configuration对象中提供给sqlSessionFactory对象随时使用。这里我们需要补充讲一下mybaits是怎么使用XMLStatementBuilder类的对象的parseStatementNode函数借用MapperBuilderAssistant类对象builderAssistant的addMappedStatement解析MappedStatement并将其关联到Configuration类对象的:

[java] view plain copy

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);

}

由以上代码可以看出mybaits使用XPath解析mapper的配置文件后将其中的resultMap、parameterMap、cache、statement等节点使用关联的builder创建并将得到的对象关联到configuration对象中,而这个configuration对象可以从sqlSession中获取的,这就解释了我们在使用sqlSession对数据库进行操作时mybaits怎么获取到mapper并执行其中的sql语句的问题。

1条大神的评论

  • avatar
    访客 2022-07-05 下午 06:30:52

    er((Class?) type); } @SuppressWarnings("unchecked") // type drives generics here TypeHandlerT returned = (TypeHandlerT) handler; retur

发表评论