mybatis 多表查詢
- mybatis實現多表查詢方式
1.1 業務裝配,對兩個表編寫單表查詢語句,在業務把查詢的兩個結果進行關聯
1.2 使用Auto Mapping 特性,在實現兩表聯合查詢時通過別名完成對映
1.3 使用mybatis的<resultMap>標籤進行實現
2.多表查詢時,類中包含另一個類的物件的分類
2.1 單個物件
2.2 集合物件
3. resultMap 標籤
3.1<resultMap>標籤寫在mapper.xml中,由程式設計師控制sql查詢結果與實體類的對映關係
mybatis 預設使用 Auto Mapping 特性
3.2使用<resultMap>標籤時,<select>標籤不寫 resultType 屬性,使用resultMap屬性引用<resultMap>標籤
3.3 使用 resultMap 實現單表對映關係
資料庫設計:id:1 name:老師1;id:2 name:老師2
實體類設計:public class Teacher{
private int id1;
private String name1;
}
mapper.xml 程式碼:
<resultMap type="teacher" id="myMap">
<id column="id" property="id1"/>
<result column=“name” property="name1"/>
</resultMap>
<select id="selAll" resultMap="myMap">
select * from teacher
</select>
3.4 使用resultMap實現關聯單個物件(N+1 方式)
N+1 查詢方式,先查詢出某個表的全部資訊,根據這個表的資訊查詢另一個表的資訊
與業務裝配的區別:
在service裡寫的程式碼,由mybatis 完成裝配
實現步驟:
1.在Student 類中包含一個 Teacher物件
public class Student{
private String id;
private String name;
private int age;
private int tid;
private Teacher teacher;
}
2.在TeacherMapper.xml中提供一個查詢
<select id="selById" resultType = "teacher" parameterType="int">
select * from teacher where id=#{0}
</select>
3.在StudentMapper.xml
3.1<association>裝配一個物件使用
3.2property 物件在類中的使用名
3.3 select 通個哪個查詢查出這個物件的信心
3.4 column 把當前表的哪個列的值作為引數傳遞給另一個查詢
3.5 前提 使用 N+1 方式時,列名如果與屬性名相同可以不配置,使用AutoMapping 特性,但是mybatis預設會給列專配一次
<resultMap type="student" id="stuMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result propety="tid" column="tid"/>
<association property="teacher" select="com.yss.mapper.TeacherMapper.selById" column="tid"/>
</resultMap>
<select id="selAll" resultMap="stuMap">
select * from student
</select>
4 .使用resultMap實現關聯單個物件(聯合查詢方式)
4.1 只需要編寫一個sql,在StudentMapper.xml新增
4.1.1<association>
4.1.2 javaType 屬性:<association> 專配完之後返回一個什麼型別的物件,取值的是一個類(或者類的別名)
<resultMap type="student" id="stuMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<reslut propety="tid" column="tid"/>
<association property="teacher" javaType="Teacher">
<id property="tid" column="id"/>
<result property="tname" column="name"/>
</association>
</resultMap>
<select id="selAll" resultMap="stuMap">
select s.id, s.name,age,s.tid,t.id tid,t.name tname from student s left join teacher t on s.tid = t.id
</select>