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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

MyBatis中多表查询(N+1方式)

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

N+1查詢方式
[1]什么是N+1的查詢方式
如果沒有N+1的方式我們想要實現多表的查詢,自己書寫查詢的業務邏輯代碼(java)
mybatis希望通過自己標簽配置的方式來解決這個問題
[2]執行的操作
查詢學生所在班級的信息(一對一)
查詢班級中所有學生的信息(一對多)
使用的時候書寫標簽需要注意:
查詢出來返回的是一個對象:association
查詢出來返回的是一個集合:collection

總結: 業務裝配方式和N+1查詢方式共同點:執行SQL語句的條數上都是N+1條語句不同點:業務裝配方式:是我們自己書寫java代碼的方式進行配置的N+1方式:通過MyBatis標簽配置的方式實現的

接口
StudentMapper.java

public interface StudentMapper {//查詢所有學生的操作List<Student> selectAll();List<Student> selectMore(int clazzno); }

ClazzMapper.java

public interface ClazzMapper {//查詢指定學生所在班級的信息Clazz selectOne(int clazzno);//查詢所有班級信息List<Clazz> selectAll(); }

XML
StudentMapper.xml

<select id="selectAll" resultMap="rm1">SELECT * from student</select><resultMap id="rm1" type="student"><!--column:數據庫的列名 property:實體的屬性名--><!--如果數據庫的列明和實體類中的屬性名一致,就可以省去該標簽但是公共字段不建議省去--><id column="sid" property="sid"></id><result column="sname" property="sname"></result><result column="clazzno" property="clazzno"></result><!--select * from clazz where clazzno=?select:執行哪一個方法column:希望查詢的哪一列作為參數進行傳遞javaType:返回值類型property:把返回的結果賦值給對象中哪一個屬性--><association select="com.bjsxt.mapper.ClazzMapper.selectOne"column="clazzno" javaType="clazz" property="cla"></association></resultMap>

ClazzMapper.xml

<select id="selectAll" resultMap="rm1">SELECT * from clazz</select><resultMap id="rm1" type="clazz"><id column="clazzno" property="clazzno"></id><result column="cname" property="cname"></result><!--select:調用哪一個xml中方法column:希望那一列作為參數進行傳遞ofType:集合的泛型property:把返回的數據整體賦值給哪一個屬性--><collection select="com.bjsxt.mapper.StudentMapper.selectMore"column="clazzno" ofType="student" property="li"></collection></resultMap>

測試

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

總結

以上是生活随笔為你收集整理的MyBatis中多表查询(N+1方式)的全部內容,希望文章能夠幫你解決所遇到的問題。

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