mybatis xml 文件中对于重复出现的sql 片段可以使用标签提取出来,在使用的地方使用标签引用即可具体用法如下:

<sql id="someSQL">
        id,name
</sql>
<select id="selectSome" >
        select
       <include refid="someSQL"/>
        from t
 </select> 

在中可以使用${}传入参数,如下:

<sql id="someSQL">
        ${tableName}.id,${tableName}.name
</sql>
<select id="selectSome" >
        select
       <include refid="someSQL"><property name="tableName" value="t"/></include>
        from t
 </select> 

对于多个xml文件需要同时引用一段相同的 可以在某个xml 中定义这个 sql 代码片段,在需要引用的地方使用全称引用即可,例子如下:

ShareMapper.xml
<mapper namespace="com.company.ShareMapper">       
    <sql id="someSQL">
       id,name
    </sql>          
</mapper>

CustomMapper.xml
<mapper namespace="com.company.CustomMapper">       
    <select id="selectSome" >
        select
       <include refid="com.company.ShareMapper.someSQL"/>
        from t
    </select>          
</mapper>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐