这是我参与更文挑战的第1天,活动详情查看: 更文挑战sql
在咱们平常开发中,常常会遇到不少sql语句大部分都是重复的问题,每次咱们新建一条相似的sql都须要copy以前写过的sql,或者其余同事写过的sql来进行修改,若是sql语句比较简短,过程其实还能接受,可是,若是sql 十分冗长,那过程不言而喻,确定是比较痛苦的,同时,也会致使咱们的xml文件比较庞大,看上去比较杂乱,不易维护,为此,Mybatis引入sql include的用法,就是用来解决该问题,将咱们重复部分的sql提取出来,简化咱们的开发,提高开发效率,同时让咱们的文件看着更加整洁,代码更易于维护markdown
1,mybatis xml 文件中对于重复出现的sql 片断可使用标签提取出来,在使用的地方使用标签引用便可具体用法以下:mybatis
<sql id="testSQL">
id,name
</sql>
<select id="selectSome" >
select
<include refid="testSQL"/> from user
</select>
复制代码
2,可在提取出来的sql中使用 ${}传入参数,操做以下app
<sql id="testSQL">
${tablename}.id,${tablename}.name
</sql>
<select id="selectSome" >
select
<include refid="testSQL">
<property name="tablename" value="user"></property>
</include>
from user
</select>
复制代码
3,以上两种状况仅仅实在同一文件内操做,若是,咱们须要引入其余文件中提取的sql,咱们该如何编写呢?具体操做以下post
ProductMapper.xml
<mapper namespace="com.product.ProductMapper"> <sql id="testSQL">
id,name
</sql>
</mapper>
UserMapper.xml
<mapper namespace="com.user.UserMapper">
<select id="selectList" >
select
<include refid="com.product.ProductMapper.testSQL"/> from user
</select>
</mapper>
复制代码