Mybatis高階使用

2021-10-04 07:46:24 字數 2706 閱讀 7321

mybatis的延遲載入

何為延遲載入

通過前面的學習,我們已經掌握了 mybatis中多表查詢的配置及實現,可以實現物件的關聯查 詢。實際開發過程中很多時候我們並不需要在載入使用者資訊時就一定要載入他的訂單資訊。此時 就是我們所說的延遲載入。

作用就是在需要用到資料時才進行載入,不需要用到資料時就不載入資料。延遲載入也稱懶載入.

好處能,因為查詢單錶要比關聯查 詢多張表速度要快。

應用通常情況下,一對一查詢不需要做延遲載入,一對多需要做延遲載入

一對一延遲載入實現

使用前提

需要在sqlmapconfig.xml 配置檔案中開啟延遲載入

bean類:

public class employee

public void setdept(dept dept)

public employee(int eid, string ename, dept dept)

public employee()

public employee(int eid, string ename)

public int geteid()

public void seteid(int eid)

public string getename()

public void setename(string ename)

@override

public string tostring() ';

}}sqlmapconfig.xml對映檔案:

<?xml version="1.0" encoding="utf-8" ?>

employeedao.xml 檔案

<?xml version="1.0" encoding="utf-8" ?>

select * from tb_employee,tb_dept where tb_employee.dno = tb_dept.did and eid = #

測試:

public class employeedaotest 

@test

public void selectemployeebyid() throws exception

}

一對多延遲載入實現

employeedao.xml 檔案

<?xml version="1.0" encoding="utf-8" ?>

select eid , ename , dno from tb_employee where eid = #

select * from tb_employee where dno = #

測試:

public class employeedaotest 

@test

public void selectemployeebyid1() throws exception

//立即載入 : 不管有沒有使用到關聯表中的資訊,都會去查詢關聯表 相當於 多表查詢

//延遲載入 : 如果沒有使用到關聯表中的資訊,就不會去查詢關聯表

}

mybatis的快取

什麼是快取

儲存在記憶體中的臨時資料

為什麼使用快取

減少和資料庫的互動次數,提高執行效率

應用場景

1,使用於快取

2,不適用於快取

比如:

一級快取的驗證

select

*from

tb_user

where

id = #

select * from tb_user where id = #

public class userdaotest

@test

public void selectuserbyid() throws exception

}

一級快取清空
close:可以清空一級快取

commit:可以清空一級快取

新增記錄:可以清空一級快取

刪除記錄:可以清空一級快取

修改記錄:可以清空一級快取

為了保證資料的時效性!!!

增刪改清空以及快取

mybatis的二級快取

使用步驟

注意事項

測試**

@test

public void selectuserbyid1() throws exception {

sqlsession sqlsession1 = sqlsessionfactory.opensession();

//user1儲存到sqlsession中

user user1 = userdao.selectuserbyid(1);

sqlsession1.close();

sqlsession sqlsession2 = sqlsessionfactory.opensession();

user user2 = userdao1.selectuserbyid(1);

sqlsession2.close();

MyBatis高階使用 動態SQL

mybatis精簡了元素種類,在mybatis3中,我們只需要學習以下4種元素 if choose when,otherwise trim where,set foreach 動態sql通常要做的事情就是根據條件包含where子句的一部分,比如 select from blog where stat...

mybatis高階操作

finduserbycondition resultmap usermap parametertype user select from user test username null and username if test user null and if where select findus...

Mybatis 高階對映

一對一對映 association 標籤的巢狀查詢 select id,username,useremail,user role.role id from user inner join user role on user role.role id user.id where user.id sel...