mybatis詳解 關聯查詢 一對一 一對多(5)

2021-09-26 21:17:15 字數 2607 閱讀 2048

商品訂單模型

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

注意:乙個使用者可以有多個訂單資訊,乙個訂單只能對應乙個使用者

方法1:

使用resulttype

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

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

改造pojo類

select

o.id,

o.user_id userid,

o.number,

o.createtime,

o.note,

u.username,

u.address

from

`orders` o

left join `user` u on o.user_id = u.id

測試方法:
@test

public void testqueryorderuser()

sqlsession.close();

}

結果:

使用resultmap,定義專門的resultmap用於對映一對一查詢結果。

一對一核心pojo類加對應的物件,xml配置

改造pojo類

select

o.id,

o.user_id userid,

o.number,

o.createtime,

o.note,

u.username,

u.address

from

`orders` o

left join `user` u on o.user_id = u.id

@test

public void testqueryorderuserresultmap()

sqlsession.close();

}

結果:案例:查詢所有使用者資訊及使用者關聯的訂單資訊。

使用者資訊和訂單資訊為一對多關係。

核心:pojo裡面加陣列或者集合,xml配置裡面加resultmap

sql語句:

select

u.id,

u.username,

u.birthday,

u.***,

u.address,

o.id oid,

o.number,

o.createtime,

o.note

from

`user` u

left join `orders` o on u.id = o.user_id

修改pojo類
select

u.id,

u.username,

u.birthday,

u.***,

u.address,

o.id oid,

o.number,

o.createtime,

o.note

from

`user` u

left join `orders` o on u.id = o.user_id

測試方法
@test

public void testqueryuserorder()

sqlsession.close();

}

結果:

Mybatis 一對多關聯查詢

1.配置檔案 select u.id u.username u.address u.u.birthday o.id oid,o.number o.createtime o.note from user u left join order o on o.user id u.id 2.介面名字3.ret...

MyBatis 一對多關聯查詢

上篇學習了一對一關聯查詢,這篇我們學習一對多關聯查詢。一對多關聯查詢關鍵點則依然是配置resultmap,在resultmap中配置collection屬性,別忽略了oftype屬性。建立表author 表blog,構建一對多的查詢場景。建立author blog model。author類中主要是...

MyBatis 一對多雙向關聯查詢

一 為teacher實體增加相關屬性 為教師實體增加指導學生集合的屬性如下 1 privatelistsupstudents 指導學生 並為其增加setter和getter方法,這裡略過。為實現教師實體對映,應先建立對映器介面如下 1 2 3 4 5 package importcom.abc.do...