mybatis xml 映射文件 sql include 的用法

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>
發佈了52 篇原創文章 · 獲贊 32 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章