mybatis系列(三) 抽取SQL片段-优化SQL

1542 0.6~0.7 分钟 260

如果某些 sql 片段在多个 sql 语句中被复用, 可以将这些 sql 片段抽取为一个单独的映射文件 (例如 SQL 语句中 *, 都尽可能用具体的字段名代替, 以提高执行效率, 这个过程中会出现大量重复 sql 片段).

抽取片段

<!-- 为何要抽取以下片段,去除SQL语句中的*,可以提高执行效率 -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace(命名空间):映射文件的唯一标识 -->
<mapper namespace="CommonSQL">
    <!-- 通过sql标签>id唯一标识片段 -->
	<sql id="commonSql">
		id,user_name,
			password,
			name,
			age,
			sex,
			birthday,
			created,
			updated
	</sql>
</mapper>

引用片段

  • mybatis-config.xml
<mappers>
    <mapper resource="CommonSQL.xml"
</mappers>
  • 需要使用片段的映射文件:在需要使用该sql片段的地方通过include标签的refid属性引用该sql片段:
	<!-- <sql id="commonSql">
		id,user_name,
			password,
			name,
			age,
			sex,
			birthday,
			created,
			updated
	</sql> -->

	<select id="queryUsersLikeUserName" resultType="User">
		select <include refid="CommonSQL.commonSql"></include> from tb_user where user_name like '%' #{userName} '%'
	</select>