細心的朋友一定會注意到,我上次寫的那個避免n+1 select(1:1)有一個問題,那就是不能廣泛關聯多個表,因為極有可能發生兩個關聯的表有重複欄位的情況,那我們應該怎麼做呢?下午在公司前輩交給我一個方法,主要是看sqlmap.xml
首先,說一下表的欄位關聯,具體的說就是
表testquestion(id,……,titletype
)
中的欄位titletype關聯
表testquestiontype(id
,name)的主鍵id.
然後,給大家看一下PO,VO類。PO類中都是表的欄位,在此不多說,主要看testquestionVO
public class TestquestionVO extends TestQuestionPO{</p><p>/**<br /> * 題目的題型<br /> */<br />private TestquestionTypeVO testquestiontype;</p><p>public TestquestionTypeVO getTestquestiontype() {<br />return testquestiontype;<br />}<br />public void setTestquestiontype(TestquestionTypeVO testquestiontype) {<br />this.testquestiontype = testquestiontype;<br />}
最後,寫下所有有關的表的類的resultMap
<sqlMap namespace="testquestion">
<typeAlias alias="testquestionVO" type="net.winclass.modules.testquestion.vo.TestquestionVO"/>
<typeAlias alias="testquestiontype" type="net.winclass.modules.testquestion.vo.TestquestionTypeVO"/>
<resultMap class="testquestiontype
" id="questionType_Result">
<result property="id" column="id"/>
<result property="name" column="tt_name
"/>/*此處column與資料提取出的列名需一致*/
</resultMap>
<resultMap class="net.winclass.modules.testquestion.vo.TestquestionVO" id="testquestion_Result">
<result property="id" column="id"/>
……
<result property="updater" column="updater"/>
<result property="testquestiontype" column="titletype
" resultMap="testquestion.
questionType_Result
"/>
</resultMap>
<select id="selectall" resultMap="testquestion_Result">
select tt_name
,…… from tb_subjectchem ts,tb_testquestiontype tt where ts.titletype=tt.id
</select>
</sqlMap>
注意紅字部分,此處的意思是testquestion的欄位titletype關聯到testquestiontype表的主鍵,黃色部分欄位的column是testquestion表的欄位,而非testquestiontype的欄位。一句話總結,主類的resultMap中的column唯寫本類的表中的欄位,而不用寫關聯的表的欄位。同時,resultMap中的重複欄位名稱最好在sql語句中重新命名,對應的resultMap也重新命名column欄位名,這樣,在提取資料的時候就能避免重複欄位提取的是相同結果了。