通過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>
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态