同任何的代碼庫一樣,在mapper中,通常也會有一些公共的sql代碼段會被很多業務mapper.xml引用到,比如最常用的可能是分頁和數據權限過濾了,尤其是在oracle中的分頁語法。為了減少骨架性代碼,通常將它們抽象到sql中,但是肯定又不能在每個mapper中也包含,這樣就沒有意義了。此時,可以將這部分移到專門的mapper.xml中,比如common.xml,其中包含如下:
<?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"> <mapper namespace="Common"> <sql id="Common.pagingStart">
</sql> <sql id="Common.pagingEnd"> <![CDATA[ limit #{startWith,jdbcType=INTEGER},#{rows,jdbcType=INTEGER} ]]> </sql> </mapper>
然后在具體的mapper.xml可以通過namespace進行引用,如下:
<select id="queryPage" resultMap="clientPage" parameterType="java.util.Map"> <include refid="Common.pagingStart"/> <include refid="commonSelect"/> <!-- 這里有個額外的1是為了避免額外處理最后一個”,“ --> 1 <include refid="commonFrom"/> <include refid="commonWhere"/> <if test="clientId != null" > and CLIENT_ID = #{clientId,jdbcType=VARCHAR} </if> <if test="clientName != null" > and CLIENT_NAME like '%${clientName}' </if> <if test="telephone != null" > and TELEPHONE = #{telephone,jdbcType=VARCHAR} </if> order by client_id <include refid="Common.pagingEnd"/> </select>
