Mybatis的動態sql語句,聯表實現

2021-09-08 14:14:13 字數 1609 閱讀 3786

通過mybatis提供的各種標籤方法實現動態拼接sql。

需求:根據性別和名字查詢使用者

查詢sql:select * from user where 1=1 and uname like 「%劉%」 and uage = 20

if標籤測試方法

注意字串型別的資料需要要做不等於空字串校驗。

where標籤

上面的sql還有where 1=1 這樣的語句,很麻煩

可以使用where標籤進行改造

select * from user

and uname like "%"#"%" and uage = #sql中可將重複的sql提取出來,使用時用include引用即可,最終達到sql重用的目的。

把上面例子中的id, username, birthday, ***, address提取出來,作為sql片段,如下:

uid,uname,uage

select from user

and uname like "%"#"%"

and uage = #

foreach標籤

向sql傳遞陣列或list,mybatis使用foreach解析,如下:

根據多個id查詢使用者資訊

查詢sql:

select * from user where id in (1,10,24)

改造queryvo

如下圖在pojo中定義list/陣列屬性ids儲存多個使用者id,並新增getter/setter方法

$

;

測試方法如下圖:

/**商品訂單資料模型

一對一查詢

需求:查詢所有訂單資訊,關聯查詢下單使用者資訊。

注意:因為乙個訂單資訊只會是乙個人下的訂單,所以從查詢訂單資訊出發關聯查詢使用者資訊為一對一查詢。如果從使用者資訊出發查詢使用者下的訂單資訊則為一對多查詢,因為乙個使用者可以下多個訂單。

sql語句:

select user.uid,uname,uage,oid,oname,odate

from order1 left join user

on order1.uid=user.uid

方法一:使用resulttype

使用resulttype,改造訂單pojo類,此pojo類中包括了訂單資訊和使用者資訊

這樣返回物件的時候,mybatis自動把使用者資訊也注入進來了

改造pojo類

select user.uid,uname,uage,oid,oname,odate

from user right join order1

on order1.uid=user.uid

測試方法:

mybatis 動態SQL語句

一 concat字串拼接 1.sql中字串拼接 select from tablename where name like concat concat 2.使用 代替 select from tablename where name like 解析過來的引數值不帶單引號,解析傳過來引數帶單引號。二 ...

Mybatis動態sql語句

finduserbycondition resultmap usermap select from user test username null and username if test user null and if where select 元素只會在子元素有返回內容的時候才會插入where...

MyBatis動態SQL語句

關鍵字 ifwhere trim foreach set if 如果傳入的p1 不為空,那麼才會sql才拼接id where mybatis的where標籤是對sql語句做了處理,當它遇到and或者or這些,where自己就給處理了。select from test t and username l...