2016-01-13 432 views
0

我在我的類中有列表,所以我在映射結果時使用了集合標記。下面是一個示例代碼:用mybatis收集resultMap的性能問題

<select id="retrieveClassRoomsWithStudents" resultMap="classroomMapper"> 
    SELECT CLS.CLASSROOMCODE, CLS.CLASSROOMNAME 
    FROM TMP.CLASSROOM CLS 
    ORDER BY CLS.CLASSROOMNAME 
</select> 

<select id="retrieveStudents" resultMap="studentMapper" parameterType="Integer" > 
    SELECT STD.CLASSROOMCODE, STD.STUDENTNUMBER, STD.STUDENTNAME 
    FROM TMP.STUDENTS STD 
    WHERE STD.CLASSROOMCODE = #{CLASSROOMCODE} 
    ORDER BY STD.STUDENTNUMBER 
</select> 

<resultMap id="classroomMapper" type="ClassroomEntity" > 
    <result property="classroomName" column="CLASSROOMNAME" /> 
    <result property="classroomCode" column="CLASSROOMCODE" /> 
    <collection property="studentList" column="CLASSROOMCODE" javaType="ArrayList" ofType="StudentEntity" select="retrieveStudents" /> 
</resultMap> 

<resultMap id="studentMapper" type="StudentEntity" > 
    <result property="classroomCode" column="CLASSROOMCODE"/> 
    <result property="studentNumber" column="STUDENTNUMBER"/> 
    <result property="studentName" column="STUDENTNAME"/> 
</resultMap> 

我有大約200個班和10.000名學生。 「retrieveClassRoomsWithStudents」方法運行20秒。我試過左外連接以減少查詢計數。單個查詢在70毫秒內運行,但結果映射再次需要大約20秒。有什麼辦法可以改善嗎?緩存是沒有選擇的,我被要求在一個回覆中返回所有學生。

回答

1

這是着名的1 + N選擇問題。你可以使用嵌套的resultmap來解決這個問題:

<resultMap id="classroomMapper" type="ClassroomEntity" > 
    <result property="classroomName" column="CLASSROOMNAME" /> 
    <result property="classroomCode" column="CLASSROOMCODE" /> 
    <collection property="studentList" resultMap="studentMapper" /> 
</resultMap> 
+0

不錯,但爲了正常運行,必須將classroomCode屬性添加爲id標記,而不是結果標記。這讓Mybatis按預期分組結果。 – jmad