MyBatis的基本用法

2021-08-19 22:30:13 字數 2957 閱讀 4451

一:mybatis的體系結構

mybatis的持久化解決方案將使用者從原始的jdbc訪問中解放出來,使用者只需要定義需要操作的sql語句,無需關注底層的jdbc操作,就可以以物件導向的方式進行持久化操作。底層資料庫連線的獲取、資料庫訪問的實現、事務控制等都無需使用者關心。

mybatis常用的兩個物件:sqlsessionfactory和sqlsession。

sqlsessionfactory:單個資料庫對映關係經過編譯後的記憶體映象。執行緒安全,是sqlsession的工廠。

sqlsession:執行持久化操作的物件,應用程式與持久儲存層之間互動操作的乙個單執行緒物件,sqlsession物件完全包含以資料庫為背景的所有執行sql操作的方法,底層封裝了jdbc連線,可以使用sqlsession例項直接執行以對映的sql語句。

二:例項

1、 測試select、insert、update、delete操作:

一:配置mybatis-config.xml檔案

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

<?xml version="1.0" encoding="iso-8859-1"?>

select * from tb_user where id = #

update tb_user

set name =#, ***=#,age=#

where id=#

delete from tb_user where id=#

三:測試

1、插入測試

public class inserttest 

}

2、查詢測試

public class selecttest 

}

3、更新測試

public class updatetest 

}

4、刪除測試

public class deletetest 

}

為了方便的獲得sqlsession物件,寫了乙個工具類:

public class fksqlsessionfactory catch(exception e)

}public static sqlsession getsqlsession()

public static sqlsessionfactory getsqlsessionfactory()

}

2、例項    測試resultmaps

resultmap元素是mybatis最重要的元素,告訴mybatis將從結果集中取出的資料轉換成開發者所需要的物件。

1、建立班級和學生表

create table tb_clazz(

id int primary key auto_increment,

code varchar(18)

);insert into tb_clazz(code) values('j1601');

insert into tb_clazz(code) values('j1602');

create table tb_student(

id int primary key auto_increment,

name varchar(18),

*** char(18),

age int,

clazz_id int,

foreign key(clazz_id) references tb_clazz(id)

);insert into tb_student(name,***,age,clazz_id) values('jack','男',22,1);

insert into tb_student(name,***,age,clazz_id) values('tom','女',22,1);

insert into tb_student(name,***,age,clazz_id) values('lucy','女',22,2);

insert into tb_student(name,***,age,clazz_id) values('nacy','男',22,2);

2、建立pojo物件    

public class clazz
public class student
查詢所有學生資訊

select * from tb_clazz where id =#

select * from tb_student

查詢所有的班級資訊

public class clazz

select * from tb_student where clazz_id =#

select * from tb_clazz

4、測試

public class selectstudenttest 

// 提交事務

session.commit();

// 關閉session

session.close();

}}

public class selectclazztest 

} // 提交事務

session.commit();

// 關閉session

session.close();

}}

MyBatis的模糊查詢的基本用法

1.模糊查詢 使用 符號,有點像el表示式,用在單引號裡面的,強制理解為乙個變數 select from emp where ename like a select from emp where ename like 但是,以上的方法有誤,解決方法,在dao層傳遞字串 name public lis...

mybatis中in的用法

1.要根據乙個list中所有id來進行查詢 public listfindinfobyadapterids list aidlist select d.i type,d.vc name,h.i time,h.i controlcode,h.i reason,h.i usertype,h.i auth...

mybatis標籤用法

一 mybatis中的標籤 1.if標籤的用法 select from wx act deadbeat order grab where 1 1 and debt no and grabor id 注 這種我們可以把所有的屬性都加上,然後跟據不同需求使用,比較靈活 2.where標籤的用法 sele...