日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MyBatis中多表查询(多表查询语句实现)重点

發布時間:2023/12/3 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis中多表查询(多表查询语句实现)重点 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

–查詢所有學生所在班級的信息(一對一)
–班級查詢學生的操作(一對多)
–遇到的問題:
查詢的SQL語句非常的簡單,但是如何把查詢的數據接受這個就是一個問題
[1]把每一個實體中的字段拿出來組建成一個新的實體 返回還是resultType
存在的問題:映射的內容會出現重復的字段
[2] resultMap:映射的操作
接口
StudentMapper.java

public interface StudentMapper {//多表查詢操作List<Student> selectAll2(); }

ClazzMapper.java

public interface ClazzMapper {//多表查詢班級學生信息List<Clazz> selectAll2(); }

XML
StudentMapper.xml

<select id="selectAll2" resultMap="rm2">SELECT * FROM student s JOIN clazz c ON s.clazzno=c.clazzno</select><resultMap id="rm2" type="student"><!--注意:書寫的每一個值就是接受數據庫查詢的數據所以想要接受的數據的字段不可以省去--><id column="sid" property="sid"></id><result column="sname" property="sname"></result><result column="clazzno" property="clazzno"></result><association property="cla" javaType="clazz"> //‘cla’student表中的clazz對象<id column="clazzno" property="clazzno"></id><result column="cname" property="cname"></result></association></resultMap>

Clazzmapper.xml

<select id="selectAll2" resultMap="rm2">SELECT * FROM student s JOIN clazz c ON s.clazzno=c.clazzno</select><resultMap id="rm2" type="clazz"><id column="clazzno" property="clazzno"></id><result column="cname" property="cname"></result><collection property="li" ofType="student"> //‘li’ clazz表中的學生集合 <id column="sid" property="sid"></id><result column="sname" property="sname"></result><result column="clazzno" property="clazzno"></result></collection></resultMap>

測試

//[4]執行方法StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);ClazzMapper claMapper = sqlSession.getMapper(ClazzMapper.class);//查詢所有學生所在的班級的信息/*List<Student> list = stuMapper.selectAll2();for(Student student:list){System.out.println(student);}*/List<Clazz> list = claMapper.selectAll2();for(Clazz clazz:list){System.out.println(clazz);}

4、Auto_Mapping
數據注入的方式
[1]自動注入方式 Auto_Mapping (自己封裝的實體屬性和數據庫的字段是一樣的情況Mybatis會自動的注入)
[2]手動注入的方式 resultMap
作用:解決自己做的實體的封裝和數據庫的字段不一致的問題
5、resultType和resultMap使用場景
[1]如果你做的是單表的查詢并且封裝的實體和數據庫的字段一一對應 resultType
[2]如果實體封裝的屬性和數據庫的字段不一致 resultMap
[3]使用的是多表的聯合查詢 resultMap
[4]使用N+1查詢的時候 resultMap

總結

以上是生活随笔為你收集整理的MyBatis中多表查询(多表查询语句实现)重点的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。