Mybatis的一对多查询
生活随笔
收集整理的這篇文章主要介紹了
Mybatis的一对多查询
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
表如下:
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;//增加學生屬性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
<!--一對多--><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>這里一個班級對應多個學生,所以將學生以List<Student>作為屬性。將兩個類相關聯。
測試結果:
如果再加上studentCard的話
StudentMapper.xml
改了一下select語句
測試結果:
班級編號:1,班級名:軟件161, 學生姓名:王富貴,編號:1,班級編號:1,cardid:1,cardinfo:學生公交卡 學生姓名:曾小賢,編號:3,班級編號:1,cardid:3,cardinfo:學生購物卡延遲加載
如果不采用延遲加載,在加載時,會將所有信息全部查詢出來,無論你是否需要。這種情況在數據量很大時,會大大增加查詢時間。降低效率。
使用延遲加載,先查詢需要的數據,其他數據在需要時再加載。
設置延遲加載:
StudentMapper.xml
解釋:重點標簽
<collection property="students" ofType="Student" select="selectStudentByCid" column="cid"></collection>這里的select中是需要延遲加載的語句,column是關聯外鍵
此外還需要在config.xml中配置開啟懶加載
config.xml
測試結果:
總結
以上是生活随笔為你收集整理的Mybatis的一对多查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis的一对一查询以及延迟加载
- 下一篇: VUE跨域问题的解决(没有config目