MyBatis中多表查询(多表查询语句实现)重点
生活随笔
收集整理的這篇文章主要介紹了
MyBatis中多表查询(多表查询语句实现)重点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
–查詢所有學生所在班級的信息(一對一)
–班級查詢學生的操作(一對多)
–遇到的問題:
查詢的SQL語句非常的簡單,但是如何把查詢的數據接受這個就是一個問題
[1]把每一個實體中的字段拿出來組建成一個新的實體 返回還是resultType
存在的問題:映射的內容會出現重復的字段
[2] resultMap:映射的操作
接口
StudentMapper.java
ClazzMapper.java
public interface ClazzMapper {//多表查詢班級學生信息List<Clazz> selectAll2(); }XML
StudentMapper.xml
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中多表查询(多表查询语句实现)重点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 秦霄贤个人简介 秦霄贤的介绍
- 下一篇: 古巴比伦灭亡的原因 古巴比伦为什么灭亡