Mybatis如何获取SQL语句
一、获取映射文件xml
在我们的mybatis-config.xml文件里面,有这么一个标签
众所周知,这个绑定的是写SQL语句的文件,所以说,谁去解析的上面的这个xml文件,谁就能拿到SQL语句
那这个文件将会被哪个标签或者哪个类加载呢?我们知道UserMapper.xml文件包含在mappers标签中,那么谁去解析mappers这个标签就能拿到这个文件所以内容。
在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。
我们查看mappers标签,发现mybatis提供了4种方法找映射文件。
与此同时,查看官方文档,官方给出了具体的使用方法。
但是,这四种哪一种的优先级的级别最高呢?
我们继续查看源码。我们来到上一讲的解析 configuration 标签下的所有属性配置的函数方法下面,
/**
找到对mappers解析的代码,mapperElement()
我们在里面可以查看到,mybatis对于映射方法的优先级确定。
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
// 加载mapper的4种方式,分别为package、resource、url、class,优先级从前往后
for (XNode child : parent.getChildren()) {
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”);
// 解析resource
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();
// 解析url
} 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();
// 解析mapperClass
} 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.”);
}
}
}
}
}
我们先得到参数列表中的context值,
SELECT * FROM User where id = #{id}发现,这正是mapper文件的内容。所以我们就已经拿到了mapper文件的内容,接下来的就是需要解析mapper文件里面的标签,拿到SQL语句。
三、得到SQL语句
我们继续查看上面对mapper文件解析的java代码,发现了两个可能与SQL语句相关的代码
sqlElement(context.evalNodes(“/mapper/sql”));
buildStatementFromContext(context.evalNodes(“select|insert|update|delete”));
1
2
我们先深入查看第一行代码,
private void sqlElement(List list) throws Exception {
//从这里开始看
if (configuration.getDatabaseId() != null) {
sqlElement(list, configuration.getDatabaseId());
}
sqlElement(list, null);
}
sqlElement(list, configuration.getDatabaseId());
1
的解析过程如下:
private void sqlElement(List list, String requiredDatabaseId) throws Exception {
// 开始遍历每1个子节点
for (XNode context : list) {
// 获取databaseId属性
String databaseId = context.getStringAttribute(“databaseId”);
// 获取id属性
String id = context.getStringAttribute(“id”);
// 添加上namespace构成完整路径
id = builderAssistant.applyCurrentNamespace(id, false);
// 继续处理
if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
// 添加到这里
sqlFragments.put(id, context);
//添加进去
}
//结束
}
//结束
}
sqlElement(list, null);
1
这个一般不处理。
我们再查看第二行代码buildStatementFromContext
private void buildStatementFromContext(List list) {
if (configuration.getDatabaseId() != null) {
buildStatementFromContext(list, configuration.getDatabaseId());
}
buildStatementFromContext(list, null);
}
四、对SQL语句的处理
我们得到SQL语句,那么我们接下来的就是需要怎么执行它。
我们继续深入,发现myabtis对list中内容进行进一步的处理,一路深入,我们得到了一个核心方法
public void parseStatementNode() {
String id = context.getStringAttribute(“id”);
String databaseId = context.getStringAttribute(“databaseId”);
if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
return;
}
String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
boolean useCache = context.getBooleanAttribute("useCache", isSelect);
boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);
// Include Fragments before parsing
XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
includeParser.applyIncludes(context.getNode());
String parameterType = context.getStringAttribute("parameterType");
Class> parameterTypeClass = resolveClass(parameterType);
String lang = context.getStringAttribute("lang");
LanguageDriver langDriver = getLanguageDriver(lang);
// Parse selectKey after includes and remove them.
processSelectKeyNodes(id, parameterTypeClass, langDriver);
// Parse the SQL (pre: and were parsed and removed)
KeyGenerator keyGenerator;
String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
if (configuration.hasKeyGenerator(keyStatementId)) {
keyGenerator = configuration.getKeyGenerator(keyStatementId);
} else {
keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
}
// sql语句的拼装
SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
Integer fetchSize = context.getIntAttribute("fetchSize");
Integer timeout = context.getIntAttribute("timeout");
String parameterMap = context.getStringAttribute("parameterMap");
String resultType = context.getStringAttribute("resultType");
Class> resultTypeClass = resolveClass(resultType);
String resultMap = context.getStringAttribute("resultMap");
String resultSetType = context.getStringAttribute("resultSetType");
ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
if (resultSetTypeEnum == null) {
resultSetTypeEnum = configuration.getDefaultResultSetType();
}
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
String resultSets = context.getStringAttribute("resultSets");
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}
上面的代码是将xml文件中标签内容解析出来,然后再调用builderAssistant.addMappedStatement()方法,将他们拼接在一起,并封装成一个类MappedStatement,然后在MapperBuilderAssistantClass中放入configuration中
MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);