<sql> 节点的基础
对于 <sql> 节点, 很多人的理解估计就是用来包含数据库的字段的, 以便用来替换所有字段 「*」 符号, 以此来提高 SQL 的执行速度。
类似这样
<sql id="Base_Column_List">
student_id, name, phone, email, sex, locked, gmt_created, gmt_modified
</sql>
但是在 mybatis 的定义中, <sql> 节点是用来定义可重用的 SQL 代码段。
它可以被包含在其他语句里面, 使用 <include> 节点来包含。
而且, 它里面是可以使用 ${} 占位符参数化的(注意, 此处的参数不是调用时传进来的), 不同的属性值通过包含的实例而变化。
比如
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
因此, 我们在连接查询时, 就不用手写那么多的别名了
<select id="selectUsers" resultType="map">
select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from some_table t1
cross join some_table t2
</select> 
<include> 节点
看一下 include 的约束:

可以看待, 必须要有 refid, 可以有0个或多个 property。 通过 property 标签, 将我们的属性包含进来。 如以上的
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
占位符也可以被用在 <include> 元素的 refid 属性里
<include refid="${include_target}"/>
<sql> 节点包含的节点
在 <sql> 节点内部, 还能包含很多节点

所有的动态 SQL 相关的节点都是可以有的。
用的最多的就是 <include> 节点。
<sql id="sometable">
${prefix}Table
</sql>
<sql id=“someinclude”>
from
<include refid="${include_target}"/>
</sql>
<select id=“select” resultType=“map”>
select
field1, field2, field3
<include refid=“someinclude”>
<property name=“prefix” value=“Some”/>
<property name=“include_target” value=“sometable”/>
</include>
</select>
本文详细介绍了MyBatis中的<sql>节点和<include>节点的作用及使用方法。通过<sql>节点可以定义可重用的SQL代码片段,并通过<include>节点引入这些代码片段,简化SQL语句编写,特别是在进行连接查询时能有效减少别名的重复书写。
570

被折叠的 条评论
为什么被折叠?



