Mybatis的一对多查询
生活随笔
收集整理的這篇文章主要介紹了
Mybatis的一对多查询
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
表如下:
create table student(sid int(11) primary key not null, sname varchar(20), cardid int(11));create table studentclass(cid int primary key not null,cname varchar(20) ); alter table student add column cid int;alter table student add constraint fk_student_studentclass foreign key(cid) references studentclass(cid);以student和studentClass為例
package entity;import java.util.List;/*** @ClassName:StudentClass* @Description:* @author:zgy19* @data:2020/1/14 16:36* @History:* @UpdateDate:* @author:* @UpdateContent:*/ public class StudentClass {private Integer cid;private String cname;//增加學(xué)生屬性List<Student> students;public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}public StudentClass(Integer cid, String cname, List<Student> students) {this.cid = cid;this.cname = cname;this.students = students;}public StudentClass() {}}StudentMapper.xml
<!--一對(duì)多--><select id="TestOneForMore" resultMap="studentclass_student_map">SELECT c.*,s.* from studentclass c inner join student son c.cid=s.cidwhere c.cid=#{cid}</select><resultMap id="studentclass_student_map" type="entity.StudentClass"><id property="cid" column="cid"></id><result property="cname" column="cname"></result><collection property="students" ofType="Student"><id property="sid" column="sid"></id><result property="sname" column="sname"></result><result property="cardid" column="cardid"></result><result property="cid" column="cid"></result><association property="studentCard" javaType="entity.StudentCard"><id property="cardid" column="cardid"></id><result property="cardinfo" column="cardinfo"></result></association></collection></resultMap>這里一個(gè)班級(jí)對(duì)應(yīng)多個(gè)學(xué)生,所以將學(xué)生以List<Student>作為屬性。將兩個(gè)類相關(guān)聯(lián)。
測(cè)試結(jié)果:
如果再加上studentCard的話
StudentMapper.xml
改了一下select語句
測(cè)試結(jié)果:
班級(jí)編號(hào):1,班級(jí)名:軟件161, 學(xué)生姓名:王富貴,編號(hào):1,班級(jí)編號(hào):1,cardid:1,cardinfo:學(xué)生公交卡 學(xué)生姓名:曾小賢,編號(hào):3,班級(jí)編號(hào):1,cardid:3,cardinfo:學(xué)生購物卡延遲加載
如果不采用延遲加載,在加載時(shí),會(huì)將所有信息全部查詢出來,無論你是否需要。這種情況在數(shù)據(jù)量很大時(shí),會(huì)大大增加查詢時(shí)間。降低效率。
使用延遲加載,先查詢需要的數(shù)據(jù),其他數(shù)據(jù)在需要時(shí)再加載。
設(shè)置延遲加載:
StudentMapper.xml
解釋:重點(diǎn)標(biāo)簽
<collection property="students" ofType="Student" select="selectStudentByCid" column="cid"></collection>這里的select中是需要延遲加載的語句,column是關(guān)聯(lián)外鍵
此外還需要在config.xml中配置開啟懶加載
config.xml
測(cè)試結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的Mybatis的一对多查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis的一对一查询以及延迟加载
- 下一篇: VUE跨域问题的解决(没有config目