1. include标签基础
<include>标签是Mybatis中用于代码重用的关键元素,它可以将一个SQL片段嵌入到另一个SQL语句中。其基本语法如下:
<include refid="fields"/>
其中,snippetId是被引用的SQL片段的唯一标识符,它应当指向一个预先定义好的SQL片段的id属性。
2. 具体使用
2.1 同一个namespace下引用sql片段
具体来说:就是把可能多次使用的SQL片段封装到一个sql标签中,冠以id,需要使用时便以include标签把其内容拉取过来。
比如下文的XML中:
<mapper namespace="com.hy.dao.PersonMapper">
<!-- select id,name,f1,f2,f3 from person where id=#{id} -->
<select id="fetchOne" resultType="com.hy.entity.Person">
select
<!-- 通过<include>标签引用上述定义的SQL片段 -->
<include refid="fields"/>
from person where id=#{id}
</select>
<!-- 定义SQL片段,通常在一个单独的<sql>标签中完成 -->
<sql id="fields">
id,name,f1,f2,f3
</sql>
</mapper>
2.2 使用<include refid>跨命名空间引用sql片段
在MyBatis中,<include>
标签通常用于在一个SQL映射文件中引用另一个SQL片段。如果想跨命名空间引用SQL片段,可以通过指定完整的命名空间和引用的ID来实现
假设你有两个SQL映射文件,分别在不同的命名空间下定义了SQL片段。
namespace1.xml
<mapper namespace="com.example.mapper.Namespace1">
<sql id="commonSelect">
SELECT id, name
</sql>
</mapper>
namespace2.xml
<mapper namespace="com.example.mapper.Namespace2">
<sql id="commonCondition">
WHERE active = 1
</sql>
</mapper>
这里在namespace2.xml
中引用namespace1.xml
中的commonSelect
SQL片段:
<mapper namespace="com.example.mapper.Namespace2">
<sql id="combinedSql">
<include refid="com.example.mapper.Namespace1.commonSelect"/>
<include refid="com.example.mapper.Namespace2.commonCondition"/>
</sql>
<sql id="commonCondition">
WHERE active = 1
</sql>
</mapper>
注意事项:
确保命名空间和ID完全匹配:在
refid
属性中,你需要完整地指定命名空间和ID,中间用点.
分隔。文件位置和加载顺序:确保你的MyBatis配置正确加载了包含这些SQL片段的映射文件。通常,这涉及到在MyBatis的配置文件中正确配置这些映射文件的路径。
配置文件路径:如果你的项目结构允许,确保所有相关的XML文件都正确放置在MyBatis可以访问的路径下。例如,在Spring Boot项目中,你通常需要在
src/main/resources
目录下放置这些XML文件,并在application.properties
或application.yml
中正确配置MyBatis的mapperLocations。
示例配置(Spring Boot):
如果你使用Spring Boot,你的application.properties
或application.yml
文件中可能包含如下配置:
application.properties
mybatis.mapper-locations=classpath*:mappers/**/*.xml
application.yml
mybatis:
mapper-locations: classpath*:mappers/**/*.xml
确保路径正确指向包含你的映射文件的目录。这样MyBatis就能找到并加载这些文件,从而允许你跨命名空间引用SQL片段。
2.3 <include>引用含有参数的sql片段
<sql id="cast_integer">
<if test="_databaseId == 'db2'">
INT (RAND () * ${range})
</if>
<if test="_databaseId == 'dm'">
CAST((RAND () * ${range}) AS INTEGER)
</if>
</sql>
<insert id="exampleInsert" parameterType="java.util.Map">
INSERT INTO tset_table (tset_column)
VALUES (
<include refid="cast_integer">
<property name="range" value="10000"/>
</include>
)
</insert>
<insert id="anotherExampleInsert" parameterType="java.util.Map">
INSERT INTO another_table (another_column)
VALUES (
<include refid="cast_integer">
<property name="range" value="100"/>
</include>
)
</insert>