Mybatis源码07 - 动态SQL的使用和原理(重要)
动态SQL的使用和原理(重要)
文章目录
- 动态SQL的使用和原理(重要)
- 一:动态SQL官方使用参考
- 1:if
- 2:choose、when、otherwise
- 3:trim, where, set
- 4:foreach
- 5:script
- 6:bind
- 7:多数据库支持
- 8:动态 SQL 中的插入脚本语言
- 二:动态SQL解析原理
- 1:关于动态SQL的接口和类
- 1.1:SqlNode接口
- 1.2:SqlSource源接口
- 1.3:BoundSql类
- 1.4:XNode类
- 1.5:BaseBuilder接口
- 1.6:LanguageDriver接口
- 2:源码分析
动态 SQL 是 MyBatis 的强大特性之一。
如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦
例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。
利用动态 SQL,可以彻底摆脱这种痛苦
一:动态SQL官方使用参考
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言, 而MyBatis 显著地提升了这一特性的易用性。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。
在 MyBatis 之前的版本中,需要花时间了解大量的元素。
借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少
1:if
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:
<select id="findActiveBlogWithTitleLike" resultType="Blog">
select * from blog where state = 'active'
<!-- 如果title字段不是null, 将会拼接成为对应的查询条件 -->
<if test="title != null">
and title like #{title}
</if>
</select>
这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;
如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果
如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称
接下来,只需要加入另一个条件即可:
<select id="findActiveBlogLike" result="Blog">
select * from blog where state = 'active'
<if test="title != null">
and title like #{title}
</if>
<if test="author != null and author.name != null">
and author_name like #{author.name}
</if>
</select>
2:choose、when、otherwise
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。
针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
<select id="findActiveBlogLike" resultType="Blog">
select * from blog where state="active"
<choose>
<when test="title != null">
and title like #{title}
</when>
<when test="author != null and author.name != null">
and author_name like #{author.name}
</when>
<otherwise>
and featured = 1
</otherwise>
</choose>
</select>
3:trim, where, set
前面几个例子已经合宜地解决了一个臭名昭著的动态 SQL 问题。
现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件
<select id="findActiveBlogLike" resultType="Blog">
select * from blog where
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
and title like #{title}
</if>
<if test="author != null and author.name != null">
and author_name like #{author.name}
</if>
</select>
如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:
select * from blog where
这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:
select * from blog where and title like "someTitle"
这个查询也会失败。这个问题不能简单地用条件元素来解决。
MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:
<select id="findActiveBlogLike" resultType="Blog">
select * from blog
<where>
<if test="state != null">
state=#{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。
比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="where" prefixOverrides="and|or">
...;
</trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。
上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
用于动态更新语句的类似解决方案叫做 set。
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列
<update id="updateAuthorIfNecessary">
update author
<set>
<if test="username != null">
username = #{username}
</if>
<if test="password != null">
password = #{password}
</if>
</set>
</update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
<!-- 设置前缀为set, 设置后缀为, -->
<!-- update table_name set xxx = yyy, ttt = zzz -->
<trim prefix="set" suffixOverrides=",">
...
<trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
4:foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
select * from post as p where id in
<!-- item -->
<foreach item="item" index="index" collection="list" open="(", separator="," close=")">
#{item}
</foreach>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量
它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符
- item 属性用于指定每次迭代中当前元素的别名。在循环体内部,你可以使用这个别名来引用当前正在处理的集合元素。
- index 属性用于指定当前迭代的索引值的别名。对于数组和列表,index 表示当前元素的索引(从 0 开始);对于 Map,index 表示当前键值对的键。
- collection 属性指定要遍历的集合对象。这个集合可以是数组、列表、Set 或者 Map 等。在 Java 应用中,这个集合通常是作为参数传递给方法或者存储在某个对象中的。
- open 属性指定循环开始时要输出的字符串。通常用于添加一些前缀,比如在 SQL 语句中,可能需要在循环结果前添加一个左括号。
- separator 属性指定每次迭代之间要输出的分隔符。在循环遍历集合时,会在每个元素之间插入这个分隔符。
- close 属性指定循环结束时要输出的字符串。通常用于添加一些后缀,比如在 SQL 语句中,可能需要在循环结果后添加一个右括号。
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。
当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。
当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值
5:script
要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素
@Update({"<script>",
"update Author",
" <set>",
" <if test='username != null'>username=#{username},</if>",
" <if test='password != null'>password=#{password},</if>",
" <if test='email != null'>email=#{email},</if>",
" <if test='bio != null'>bio=#{bio}</if>",
" </set>",
"where id=#{id}",
"</script>"})
void updateAuthorValues(Author author);
6:bind
bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。
<select id="selectBlogList" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'"/>
select * from blog where title like #{pattern}
</select>
7:多数据库支持
如果配置了 databaseIdProvider,你就可以在动态代码中使用名为 “_databaseId” 的变量来为不同的数据库构建特定的语句。
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'oracle'">
select seq_users.nextval from dual
</if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1"
</if>
</selectKey>
insert into users values (#{id}, #{name})
</insert>
8:动态 SQL 中的插入脚本语言
MyBatis 从 3.2 版本开始支持插入脚本语言,这允许你插入一种语言驱动,并基于这种语言来编写动态 SQL 查询语句
可以通过实现以下接口来插入一种语言:
public interface LanguageDriver {
ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
}
实现自定义语言驱动后,你就可以在 mybatis-config.xml 文件中将它设置为默认语言:
<typeAliases>
<typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
</typeAliases>
<settings>
<setting name="defaultScriptingLanguage" value="myLanguage"/>
</settings>
或者,你可以使用lang属性为特定的语句指定语言
<select id="selectBlog" lang="myLanguage">
select * from blog
</select>
或者,在你的 mapper 接口上添加 @Lang 注解:
public interface Mapper {
@Lang(MyLanguageDriver.class)
@Select("select * from blog")
List<Blog> selectBlog();
}
二:动态SQL解析原理
在使用mybatis的时候,会在xml中编写sql语句。比如这段动态sql代码:
<update id="update" parameterType="org.format.dynamicproxy.mybatis.bean.User">
UPDATE users
<!-- 指定前缀为set, 后缀是, -->
<trim prefix="SET" prefixOverrides=",">
<!-- 用if标签,set对应的字段 -->
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age != null and age != ''">
, age = #{age}
</if>
<if test="birthday != null and birthday != ''">
, birthday = #{birthday}
</if>
</trim>
where id = ${id}
</update>
那么Mybatis底层是如何构造这段sql的呢
1:关于动态SQL的接口和类
1.1:SqlNode接口
简单理解就是xml中的每个标签,比如上述sql的update
, trim
, if
标签:
public interface SqlNode {
boolean apply(DynamicContext context);
}
1.2:SqlSource源接口
代表从xml文件或注解映射的SQL内容,主要就是用于创建BoundSql,有实现类DynamicSqlSource(动态SQL源),StaticSqlSource(静态SQL源)等
public interface SqlSource {
BoundSql getBoundSql(Object parameterObject);
}
1.3:BoundSql类
封装mybatis最终产生sql的类,包括sql语句,参数,参数源数据等参数
public class BoundSql {
private final String sql;
private final List<ParameterMapping> parameterMappings;
private final Object parameterObject;
private final Map<String, Object> additionalParameters;
private final MetaObject metaParameters;
}
1.4:XNode类
一个Dom API中的Node接口的扩展类
public class XNode {
private final Node node;
private final String name;
private final String body;
private final Properties attributes;
private final Properties variables;
private final XPathParser xpathParser;
}
1.5:BaseBuilder接口
这些Builder的作用就是用于构造sql
下面我们简单分析下其中4个Builder:
XMLConfigBuilder
解析mybatis中configLocation属性中的全局xml文件,内部会使用XMLMapperBuilder解析各个xml文件
XMLMapperBuilder
遍历mybatis中mapperLocations属性中的xml文件中每个节点的Builder,比如user.xml
内部会使用XMLStatementBuilder处理xml中的每个节点
XMLStatementBuilder
解析xml文件中各个节点,比如select,insert,update,delete节点,内部会使用XMLScriptBuilder处理节点的sql部分
遍历产生的数据会丢到Configuration的mappedStatements中
XMLScriptBuilder
解析xml中各个节点sql部分的Builder
1.6:LanguageDriver接口
该接口主要的作用就是构造sql
XMLLanguageDriver内部会使用XMLScriptBuilder解析xml中的sql部分
2:源码分析
SqlSessionFactoryBean ->
InitializingBean#afterPropertiesSet()
-> buildSqlSessionFactory -> XMLMapperBuilder属性解析mapperLocations属性中的各个xml文件 -> configurationElement -> buildStatementFromContext -> XMLLanguageDriver -> SqlSource -> BoundSql -> sql
Spring与Mybatis整合的时候需要配置SqlSessionFactoryBean,该配置会加入数据源和mybatis xml配置文件路径等信息
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatisConfig.xml"/>
<property name="mapperLocations" value="classpath*:org/format/dao/*.xml"/>
</bean>
SqlSessionFactoryBean实现了Spring的InitializingBean接口
InitializingBean接口的afterPropertiesSet()
方法中会调用buildSqlSessionFactory()
方法
该方法内部会使用:
- XMLConfigBuilder解析属性configLocation中配置的路径
- XMLMapperBuilder属性解析mapperLocations属性中的各个xml文件
由于XMLConfigBuilder内部也是使用XMLMapperBuilder,我们就看看XMLMapperBuilder的解析细节:
/**
* 解析配置文件
* 该方法首先检查配置是否已经加载了当前的资源,如果没有,则进行解析
* 解析过程中,会处理待解析的结果映射、缓存引用和语句
*/
public void parse() {
// 检查当前资源是否已经被加载,如果没有,则进行解析
if (!configuration.isResourceLoaded(resource)) {
// 解析<mapper>节点下的配置元素
configurationElement(parser.evalNode("/mapper"));
// 将当前资源标记为已加载
configuration.addLoadedResource(resource);
// 为解析的命名空间绑定映射器
bindMapperForNamespace();
}
// 解析剩余未处理的结果映射
parsePendingResultMaps();
// 解析剩余未处理的缓存引用
parsePendingCacheRefs();
// 解析剩余未处理的语句
parsePendingStatements();
}
/**
* 解析配置元素
* 该方法负责解析传入的XML配置元素,并根据解析结果配置当前的Mapper
* 它会依次处理namespace、cache-ref、cache、parameterMap、resultMap、sql以及具体的数据库操作(如select、insert、update、delete)
* 如果解析过程中出现错误,将抛出BuilderException异常
*
* @param context XML配置元素的封装对象,用于提取属性和节点
*/
private void configurationElement(XNode context) {
try {
// 获取Mapper的命名空间,确保不为空
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.isEmpty()) {
throw new BuilderException("Mapper的namespace不能为空");
}
builderAssistant.setCurrentNamespace(namespace);
// 解析并处理cache-ref元素,允许Mapper共享缓存配置
cacheRefElement(context.evalNode("cache-ref"));
// 解析并处理cache元素,配置Mapper的缓存策略
cacheElement(context.evalNode("cache"));
// 解析parameterMap元素,配置参数映射
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
// 解析resultMap元素,配置结果集映射
resultMapElements(context.evalNodes("/mapper/resultMap"));
// 解析sql元素,配置可重用的SQL代码块
sqlElement(context.evalNodes("/mapper/sql"));
// 解析并构建具体的数据库操作语句(select、insert、update、delete)
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
// 当解析Mapper XML出错时,抛出异常并包含错误详情
throw new BuilderException("解析Mapper XML出错。XML位置是'" + resource + "'. 原因: " + e, e);
}
}
关注一下,增删改查节点的解析:
/**
* 根据上下文构建语句列表
* 该方法首先检查是否有一个特定的数据库ID,如果有的话,它将使用该ID构建语句
* 如果没有特定的数据库ID,它将构建默认的语句
* 这种设计允许在不同数据库之间共享配置,同时仍然允许特定于数据库的配置
*
* @param list XNode对象的列表,通常包含配置信息
*/
private void buildStatementFromContext(List<XNode> list) {
// 检查是否有特定的数据库ID
if (configuration.getDatabaseId() != null) {
// 使用数据库ID构建语句
buildStatementFromContext(list, configuration.getDatabaseId());
}
// 构建默认的语句
buildStatementFromContext(list, null);
}
/**
* 从配置上下文中构建Statement对象
*
* 本方法主要负责根据提供的一组XML配置节点(list参数)和特定的数据库ID(requiredDatabaseId参数),
* 构建并解析Statement对象。它遍历配置节点列表,针对每个节点,使用XMLStatementBuilder进行解析,
* 并处理可能的不完整元素异常。
*
* @param list 包含Statement配置的XML节点列表
* @param requiredDatabaseId 数据库ID,用于限定构建Statement的数据库环境
*/
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
// 遍历配置上下文中的每个节点,以构建相应的Statement对象
for (XNode context : list) {
// 初始化XMLStatementBuilder实例,传入当前的配置、构建助手、配置节点和数据库ID
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context,
requiredDatabaseId);
try {
// 解析Statement节点,实际执行构建过程
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
// 如果解析过程中出现不完整元素异常,则将未完成的Statement添加到配置中,以待后续补全
configuration.addIncompleteStatement(statementParser);
}
}
}
上面对于每一个节点,都用XMLStatementBuilder解析,可以看下这个
默认会使用XMLLanguageDriver创建SqlSource(Configuration构造函数中设置)。
XMLLanguageDriver创建SqlSource:
/**
* 创建SQL源
*
* 本方法主要用于根据配置和脚本节点创建一个SQL源对象它使用XMLScriptBuilder来解析脚本节点,
* 并根据提供的参数类型来创建相应的SQL源
*
* @param configuration 配置对象,用于配置SQL源的设置
* @param script 脚本节点,包含动态SQL语句的XML结构
* @param parameterType 参数类型,用于指定SQL语句期望的参数类型
* @return 返回一个SqlSource对象,它包含了动态SQL语句的逻辑和参数信息
*/
@Override
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
// 创建XMLScriptBuilder实例,传入配置、脚本节点和参数类型,用于构建SQL源
XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
// 解析脚本节点,返回对应的SQL源对象
return builder.parseScriptNode();
}
/**
* XMLScriptBuilder中
* 解析脚本节点以创建SqlSource对象
* 本方法负责解析配置上下文中的动态标签,并根据解析结果创建相应的SqlSource对象
* 主要用于处理动态SQL,提供更为灵活的SQL语句处理机制
*
* @return SqlSource对象,用于后续的SQL执行和处理
*/
public SqlSource parseScriptNode() {
// 解析配置上下文中的动态标签,返回一个包含解析结果的MixedSqlNode对象
MixedSqlNode rootSqlNode = parseDynamicTags(context);
SqlSource sqlSource;
// 根据是否为动态SQL,选择创建不同的SqlSource类型
if (isDynamic) {
// 对于动态SQL,创建DynamicSqlSource对象,这允许在运行时动态生成SQL语句
sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
} else {
// 对于静态SQL,创建RawSqlSource对象,这提供了对原始SQL语句的处理
sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
}
// 返回创建的SqlSource对象
return sqlSource;
}
得到SqlSource之后,会放到Configuration中,有了SqlSource,就能拿BoundSql了,BoundSql可以得到最终的sql
以下面的xml解析大概说下parseDynamicTags的解析过程:
<update id="update" parameterType="org.format.dynamicproxy.mybatis.bean.User">
UPDATE users
<trim prefix="SET" prefixOverrides=",">
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age != null and age != ''">
, age = #{age}
</if>
<if test="birthday != null and birthday != ''">
, birthday = #{birthday}
</if>
</trim>
where id = ${id}
</update>
parseDynamicTags方法的返回值是一个List,也就是一个Sql节点集合。-> List<SqlNode>
- 首先根据update节点(Node)得到所有的子节点,这里分别是3个子节点【
update users
;trim
;where
】 - 遍历各个子节点,然后处理
- 如果节点类型是文本或者CDATA,构造一个TextSqlNode或StaticTextSqlNode
- 如果节点类型是元素,说明该update节点是个动态sql,然后会使用NodeHandler处理各个类型的子节点