1.sql語句,建立資料庫
create tableteacher
(
id
int(10) not null,
name
varchar(30) default null,
primary key (id
)
)engine=innodb default charset=utf8
insert into teacher(id
,name
) values (1,『秦老師』);
create tablestudent
(
id
int(10) not null,
name
varchar(30) default null,
tid
int(10) default null,
primary key (id
),
keyfktid
(tid
),
constraintfktid
foreign key (tid
) referencesteacher
(id
)
)engine=innodb default charset=utf8
insert intostudent
(id
,name
,tid
) values (『1』,『小明』,『1』);
insert intostudent
(id
,name
,tid
) values (『2』,『小陳』,『1』);
insert intostudent
(id
,name
,tid
) values (『3』,『小李』,『1』);
insert intostudent
(id
,name
,tid
) values (『4』,『小王』,『1』);
insert intostudent
(id
,name
,tid
) values (『5』,『小張』,『1』);
教師對學生一對多
學生對教師多對一
查詢所有學生的資訊
可以看到teacher為null
多對一:
將getstudent方法的返回型別改為resultmap
方法二:
以上就是多對一的查詢
一對多乙個老師對應多個學生
"getteacher" resultmap=
"teacherstudent"
>
select s.id sid,s.name sname,t.id tid,t.name tname
from student s,teacher t
where s.tid =t.id and t.id= #
<
/select>
"teacherstudent" type=
"com.briup.pojo.teacher"
>
"tname" property=
"name"
>
<
/result>
"tid" property=
"id"
>
<
/result>
"students" oftype=
"com.briup.pojo.student"
>
"name" column=
"sname"
>
<
/result>
"id" column=
"sid"
>
<
/result>
"tid" column=
"tid"
>
<
/result>
<
/collection>
<
/resultmap>
Mybatis 5 多對一 一對多
例子為5個學生,對應1個老師。表結構為 student的tid為外來鍵,關聯teacher的id。現要查詢所有學生,附帶上老師的資訊 包括姓名 可以用兩種方式,1.巢狀處理結果集對映 2.巢狀處理查詢 1.寫實體類 student實體類 private int id private string n...
JavaWeb mybatis一對一 一對多查詢
mybatis查詢基本返回資料基本用到的都是resulttype與resultmap,resulttype必須po類與sql欄位一致,而resultmap可以不一致通過配置對映。本篇文章一是要講解resulttype與resultmap如何使用 二是重點講解一對一與一對多查詢resultmap的使用...
Mybatis關聯查詢(一對一,一對多)
複雜查詢時,單錶對應的po類已不能滿足輸出結果集的對映。所以要根據需求建立乙個擴充套件類來作為resulttype的型別。擴充套件類 association的使用 需要在本類中新增字段如下 resulttype 使用resulttype實現較為簡單,如果pojo中沒有包括查詢出來的列名,需要增加列名...