Mybatis框架,MyBatis中resuleMap一對一和一對多屬性字段映射

 2023-10-06 阅读 29 评论 0

摘要:處理屬性和字段不一致 通過resultMap 當Java中實體類屬性和數據庫字段不一致的時候,我們可以通過resultMap進行映射,例如我們要查詢一個user表中的用戶的全部信息,在Java中屬性是password,而數據庫字段是pwd,所以我們的就引入了resultMap來

處理屬性和字段不一致

通過resultMap
當Java中實體類屬性和數據庫字段不一致的時候,我們可以通過resultMap進行映射,例如我們要查詢一個user表中的用戶的全部信息,在Java中屬性是password,而數據庫字段是pwd,所以我們的就引入了resultMap來取代resultType

<resultMap id="UserMap" type="com.com.hzy.pojo.User"><result property="id" column="id"/><result property="username" column="username"/><result property="password" column="pwd"/>
</resultMap><select id="getUserList" resultMap="UserMap">select * from user
</select>

通過SQL語句別名
在查詢指定字段的時候,把不一致的字段指定別名為Java屬性

 <select id="getUserByNameAndPassword" resultType="com.hzy.pojo.User">select id,username,pwd password from user where username = #{username} and pwd = #{password}</select>

處理復雜屬性

當出現聯表查詢的時候,會出現一對一一對多的關系
如果有兩張表,分別是學生和老師
在這里插入圖片描述
在這里插入圖片描述
站在學生的角度看,一個學生是對應一個老師的,這是一對一,在學生信息表中只有老師的id而沒有老師的名字,我們想要通過聯表查詢查詢出學生的信息和老師的名字。
此時的Student類是帶有復雜類型Teacher的類
在這里插入圖片描述
在這里插入圖片描述

那么我們在進行resultMap映射的時候,會牽扯到對象的映射,用到association標簽

<resultMap id="studentTeacher" type="com.hzy.pojo.Student"><result property="id" column="id"/><result property="studentName" column="student_name"/><association property="teacher" javaType="com.hzy.pojo.Teacher"><result property="teacherName" column="teacher_name"/></association>
</resultMap><select id="findAllStudent" resultMap="studentTeacher">SELECT s.id,s.student_name,t.teacher_name FROM student s,teacher t
</select>

Mybatis框架,如果我們站在老師的角度來看,那就是一個老師對應多個學生,這是一對多
在這里插入圖片描述
在這里插入圖片描述
此時用到一個標簽是collection

<resultMap id="teacherStudent" type="com.hzy.pojo.Teacher"><result property="id" column="id"/><result property="teacherName" column="teacher_name"/><collection property="studentList" ofType="com.hzy.pojo.Student"><result property="id" column="id"/><result property="studentName" column="student_name"/><result property="teacherId" column="teacher_id"/></collection>
</resultMap>
<select id="findAllTeacher" resultMap="teacherStudent">SELECT t.id,t.teacher_name,s.student_name FROM teacher t,student s
</select>

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/122856.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息