MyBatis的association的延遲加載如何實(shí)現(xiàn)

小樊
83
2024-08-14 15:44:39

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)步驟如下:

  1. 在Mapper文件中配置association標(biāo)簽,并設(shè)置fetchType屬性為lazy。
<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>
  1. 在查詢數(shù)據(jù)時(shí),不直接訪問(wèn)關(guān)聯(lián)實(shí)體對(duì)象,只訪問(wèn)主實(shí)體對(duì)象。
User user = sqlSession.selectOne("getUser", userId);
  1. 當(dāng)需要訪問(wèn)關(guān)聯(lián)實(shí)體對(duì)象時(shí),可以通過(guò)主實(shí)體對(duì)象的getter方法來(lái)訪問(wèn)。
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ù),提高查詢效率。

0