ibaits– 避免n+1 select (1:m;m:n)

來源:互聯網
上載者:User

      細心的朋友一定會注意到,我上次寫的那個避免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欄位名,這樣,在提取資料的時候就能避免重複欄位提取的是相同結果了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.