2016-01-03 42 views
0

我在XML文件中定義的大搜索查詢MyBatis的重用查詢來獲取COUNT(*)

<select id="searchItems" resultMap="myMap" parameterType="map"> 
SELECT 
    a lot of field 
FROM multiple table with few joins 
WHERE with few conditions 
LIMIT x,y 
</select> 

上面的查詢使用限制,能夠返回PAGINATE結果,並避免返回在整個項目搜索。但是對於一個需求,我還需要返回查詢找到的項目總數。

我的問題是:我如何重用上面的查詢,而不是隻選擇count(*),顯然沒有LIMIT?有沒有辦法將每個查詢部分分開並在<select>標記中重用它們?

回答

5

您可以提取常見的SQL和重用這樣的:

<sql id="queryUserCondition"> 
     where 1=1   
    </sql> 
    <select id="countAll" resultType="int"> 
     select count(*) from user_info <include refid="queryUserCondition" /> 
    </select> 
    <select id="findAll" resultMap="UserResultMap"> 
     select <include refid="UserColumns" /> 
     from user_info 
     <include refid="queryUserCondition" /> 
    </select>