这是我参与更文挑战的第1天,活动详情查看: 更文挑战
背景:
在我们日常开发中,经常会遇到很多sql语句大部分都是重复的问题,每次我们新建一条类似的sql都需要copy之前写过的sql,或者其他同事写过的sql来进行修改,如果sql语句比较简短,过程其实还能接受,但是,如果sql 十分冗长,那过程不言而喻,肯定是比较痛苦的,同时,也会导致我们的xml文件比较庞大,看上去比较杂乱,不易维护,为此,Mybatis引入sql include的用法,就是用来解决该问题,将我们重复部分的sql提取出来,简化我们的开发,提升开发效率,同时让我们的文件看着更加整洁,代码更易于维护
用法:
1,mybatis xml 文件中对于重复出现的sql 片段可以使用标签提取出来,在使用的地方使用标签引用即可具体用法如下:
<sql id="testSQL">
id,name
</sql>
<select id="selectSome" >
select
<include refid="testSQL"/> from user
</select>
复制代码
2,可在提取出来的sql中使用 ${}传入参数,操作如下
<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,我们该如何编写呢?具体操作如下
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>
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END