溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java中MyBatis延遲加載怎么用

發(fā)布時(shí)間:2021-09-15 12:55:13 來(lái)源:億速云 閱讀:110 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)java中MyBatis延遲加載怎么用,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

什么是延遲加載?

延遲加載也叫懶加載、惰性加載,使?延遲加載可以提?程序的運(yùn)行效率,針對(duì)于數(shù)據(jù)持久層的操作, 在某些特定的情況下去訪問(wèn)特定的數(shù)據(jù)庫(kù),在其他情況下可以不訪問(wèn)某些表,從?定程度上減少了 Java 應(yīng)?與數(shù)據(jù)庫(kù)的交互次數(shù)。

查詢學(xué)?和班級(jí)的時(shí),學(xué)生和班級(jí)是兩張不同的表,如果當(dāng)前需求只需要獲取學(xué)shengsheng的信息,那么查詢學(xué) ?單表即可,如果需要通過(guò)學(xué)?獲取對(duì)應(yīng)的班級(jí)信息,則必須查詢兩張表。 不同的業(yè)務(wù)需求,需要查詢不同的表,根據(jù)具體的業(yè)務(wù)需求來(lái)動(dòng)態(tài)減少數(shù)據(jù)表查詢的?作就是延遲加載。

如何使用延遲加載?

1.在 config.xml 中開(kāi)啟延遲加載

<settings>
 <!-- 打印SQL-->
 <setting name="logImpl" value="STDOUT_LOGGING" />
 <!-- 開(kāi)啟延遲加載 -->
 <setting name="lazyLoadingEnabled" value="true"/>
</settings>

2.將多表關(guān)聯(lián)查詢拆分成多個(gè)單表查詢

StudentRepository中

 public Student findByIdLazy(long id);

StudentRepository.xml

<resultMap id="studentMapLazy" type="entity.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <association property="classes" javaType="entity.Classes" select="repository.ClassesRepository.findByIdLazy" column="cld">
        </association>
    </resultMap>
    <select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
-- select s.id ,s.name,c.id as cid,c.name as cname from student s,classes c where s.id =1 and s.cld=c.id;
    select * from student where id=#{id};
    </select>

ClassesRepository

public Classes findByIdLazy(long id);
<resultMap id="classesMap" type="entity.Classes">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="students" ofType="entity.Student">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
        </collection>
    </resultMap>

關(guān)于“java中MyBatis延遲加載怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI