MyBatis的association的延遲加載是通過(guò)配置MyBatis的Mapper文件來(lái)實(shí)現(xiàn)的。在配置association時(shí),可以設(shè)置fetchType屬性為lazy,表示延遲加載。這樣在查詢數(shù)據(jù)時(shí),只會(huì)加載主實(shí)體對(duì)象,當(dāng)需要訪問(wèn)關(guān)聯(lián)實(shí)體對(duì)象時(shí)才會(huì)去數(shù)據(jù)庫(kù)加載關(guān)聯(lián)實(shí)體對(duì)象的數(shù)據(jù)。
具體實(shí)現(xiàn)步驟如下:
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="department" column="dept_id" javaType="Department" fetchType="lazy"/>
</resultMap>
User user = sqlSession.selectOne("getUser", userId);
Department department = user.getDepartment();
這樣就實(shí)現(xiàn)了MyBatis的association的延遲加載。當(dāng)需要訪問(wèn)關(guān)聯(lián)實(shí)體對(duì)象時(shí),MyBatis會(huì)去數(shù)據(jù)庫(kù)加載關(guān)聯(lián)實(shí)體對(duì)象的數(shù)據(jù),從而避免一次性加載所有關(guān)聯(lián)實(shí)體對(duì)象的數(shù)據(jù),提高查詢效率。