Mybatis之sqlFragment(可复用的sql片段)

2024-05-23 22:32

本文主要是介绍Mybatis之sqlFragment(可复用的sql片段),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天,我们将分析Mybatis之sqlFragment,可以翻译为sql片段,它的存在价值在于可复用sql片段,避免到处重复编写。
在工作中,往往有这样的需求,对于同一个sql条件查询,首先需要统计记录条数,用以计算pageCount,然后再对结果进行分页查询显示,看下面一个例子。

<sql id="studentProperties">
<!--sql片段-->select stud_id as studId, name, email, dob, phonefrom students
</sql>
<select id="countAll" resultType="int">select count(1) from (<include refid="studentProperties"></include><!--复用-->) tmp
</select><select id="findAll" resultType="Student" parameterType="map">select * from (<include refid="studentProperties"></include><!--复用-->) tmp limit #{offset}, #{pagesize}
</select>

这就是sqlFragment,它可以为select|insert|update|delete标签服务,可以定义很多sqlFragment,然后使用include标签引入多个sqlFragment。在工作中,也是比较常用的一个功能,它的优点很明显,复用sql片段,它的缺点也很明显,不能完整的展现sql逻辑,如果一个标签,include了四至五个sqlFragment,其可读性就非常差了。

sqlFragment里的内容是可以随意写的,它不需要是一个完整的sql,它可以是“,phone”这么简单的文本。

sqlFragment的解析过程

sqlFragment存储于Configuration内部。

protected final Map<String, XNode> sqlFragments = new StrictMap<XNode>("XML fragments parsed from previous mappers");

解析sqlFragment的过程非常简单。
org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XNode)方法部分源码。

// 解析sqlFragment
sqlElement(context.evalNodes("/mapper/sql"));
// 为select|insert|update|delete提供服务
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));

sqlFragment存储于Map<String, XNode>结构当中。其实最关键的,是它如何为select|insert|update|delete提供服务的。

select|insert|update|delete标签中,解析include标签的过程

org.apache.ibatis.builder.xml.XMLStatementBuilder.parseStatementNode()方法源码。

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

注释“pre: and were parsed and removed”,含义为解析完,并移除。为什么要移除呢?秘密都隐藏在applyIncludes()方法内部了。

org.apache.ibatis.builder.xml.XMLIncludeTransformer.applyIncludes(Node, Properties)方法源码。

  /*** Recursively apply includes through all SQL fragments.* @param source Include node in DOM tree* @param variablesContext Current context for static variables with values*/private void applyIncludes(Node source, final Properties variablesContext) {if (source.getNodeName().equals("include")) {// new full context for included SQL - contains inherited context and new variables from current include nodeProperties fullContext;String refid = getStringAttribute(source, "refid");// replace variables in include refid valuerefid = PropertyParser.parse(refid, variablesContext);Node toInclude = findSqlFragment(refid);Properties newVariablesContext = getVariablesContext(source, variablesContext);if (!newVariablesContext.isEmpty()) {// merge contextsfullContext = new Properties();fullContext.putAll(variablesContext);fullContext.putAll(newVariablesContext);} else {// no new context - use inherited fullyfullContext = variablesContext;}// 递归调用applyIncludes(toInclude, fullContext);if (toInclude.getOwnerDocument() != source.getOwnerDocument()) {toInclude = source.getOwnerDocument().importNode(toInclude, true);}// 将include节点,替换为sqlFragment节点source.getParentNode().replaceChild(toInclude, source);while (toInclude.hasChildNodes()) {// 将sqlFragment的子节点(也就是文本节点),插入到sqlFragment的前面toInclude.getParentNode().insertBefore(toInclude.getFirstChild(), toInclude);}// 移除sqlFragment节点toInclude.getParentNode().removeChild(toInclude);} else if (source.getNodeType() == Node.ELEMENT_NODE) {NodeList children = source.getChildNodes();for (int i=0; i<children.getLength(); i++) {// 递归调用applyIncludes(children.item(i), variablesContext);}} else if (source.getNodeType() == Node.ATTRIBUTE_NODE && !variablesContext.isEmpty()) {// replace variables in all attribute valuessource.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));} else if (source.getNodeType() == Node.TEXT_NODE && !variablesContext.isEmpty()) {// replace variables ins all text nodessource.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));}}

上面是对源码的解读,为了便于理解,我们接下来采用图示的办法,演示其过程。

图示过程演示

  1. 解析节点
<select id="countAll" resultType="int">select count(1) from (<include refid="studentProperties"></include>) tmp</select>
  1. include节点替换为sqlFragment节点
<select id="countAll" resultType="int">select count(1) from (<sql id="studentProperties">select stud_id as studId, name, email, dob, phonefrom students</sql>) tmp
</select>
  1. 将sqlFragment的子节点(文本节点)insert到sqlFragment节点的前面。注意,对于dom来说,文本也是一个节点,叫TextNode。

    select count(1) from (
    select
    stud_id as studId
    , name, email
    , dob
    , phone
    from students

    select
    stud_id as studId
    , name, email
    , dob
    , phone
    from students

    ) tmp

  2. 移除sqlFragment节点

<select id="countAll" resultType="int">select count(1) from (select stud_id as studId, name, email, dob, phonefrom students) tmp</select>
  1. 最终结果如图所示
    (Made In QQ截图及时编辑)
    如此一来,TextNode1 + TextNode2 + TextNode3,就组成了一个完整的sql。遍历select的三个子节点,分别取出TextNodevalueappend到一起,就是最终完整的sql。
    这也是为什么要移除 and 节点的原因。
    这就是MybatissqlFragment

这篇关于Mybatis之sqlFragment(可复用的sql片段)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/996601

相关文章

mybatis和mybatis-plus设置值为null不起作用问题及解决

《mybatis和mybatis-plus设置值为null不起作用问题及解决》Mybatis-Plus的FieldStrategy主要用于控制新增、更新和查询时对空值的处理策略,通过配置不同的策略类型... 目录MyBATis-plusFieldStrategy作用FieldStrategy类型每种策略的作

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I

在MySQL执行UPDATE语句时遇到的错误1175的解决方案

《在MySQL执行UPDATE语句时遇到的错误1175的解决方案》MySQL安全更新模式(SafeUpdateMode)限制了UPDATE和DELETE操作,要求使用WHERE子句时必须基于主键或索引... mysql 中遇到的 Error Code: 1175 是由于启用了 安全更新模式(Safe Upd

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

MyBatis-Flex BaseMapper的接口基本用法小结

《MyBatis-FlexBaseMapper的接口基本用法小结》本文主要介绍了MyBatis-FlexBaseMapper的接口基本用法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具... 目录MyBATis-Flex简单介绍特性基础方法INSERT① insert② insertSelec

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

MySql死锁怎么排查的方法实现

《MySql死锁怎么排查的方法实现》本文主要介绍了MySql死锁怎么排查的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录前言一、死锁排查方法1. 查看死锁日志方法 1:启用死锁日志输出方法 2:检查 mysql 错误