resultMap与resultType的差别

项目中进行dao层数据持久化写入时,在对应的Mapper.xml中我们会对对应返回值结果类型进行定义

ResultMap:当使用resultTypeSQL语句返回结果类型处理时,对于SQL语句查询出的字段在相应的对象中必须有相同字段的属性名相对应,例如下面的TeacherDept对象

resultType="teacherDept":一般来说需要写该类的全类名,但是在myBatis.xml中配置 了类别名扫描路径,所以这边只要写类名首字母小写就可以映射到;

<typeAliases>
        <package name="com.cmj.entity"/>
    </typeAliases>

<select id="selectTeacherDept"  resultType="teacherDept">
       SELECT
	t.id,
	t.`name` tname,
	t.pass_word,
	d.`name` dname
FROM
	teacher t
LEFT JOIN dept d ON t.dept_id = d.id
WHERE
	t.id = #{id}
       
   </select>

这边我们选择出来的teacherDept这张表,就可以对应entity中的teacherDept这类中的各个属性值

也就是表中的t.name tname中新生成表字段中定义的名字tname必须是跟teacherDept这个类中的属性名tname相一致,只有名字一样的时候,才会映射上;如果名字不一样,属性绑定不上,导致该属性为null

ResultMap当使用resultMapSQL语句返回结果类型处理时,通常需要在mapper.xml中定义resultMap进行pojo和相应表字段的对应。

也就是这个时候,我们要求的对象属性名可以不用跟数据库表进行展示的名字一模一样,可以自行定义对应的对象属性名是匹配数据库展示表中的哪个数据名()

 <!-- 联表查询 -->
   
   <resultMap type="teacherDept2" id="teacherDept">
   <result property="id" column="id"/>
   <result property="teacherName" column="tname"/>
   <result property="deptName" column="dname"/>
   <result property="passWord" column="pass_word"/>
   
   </resultMap>
    <select id="selectTeacherDept2"  resultMap="teacherDept">
       SELECT
	t.id,
	t.`name` tname,
	t.pass_word,
	d.`name` dname
FROM
	teacher t
LEFT JOIN dept d ON t.dept_id = d.id
WHERE
	t.id = #{id}
       
   </select>
   

其中我们可以看到 <result property="deptName" column="dname"/>中,其中property是该类的属性名,而column是的值是数据库中对应的数据名,这样就可以进行自行匹配

注:我们在进行联表查询时,对于查出来的表内容,我们一般会存放在一个对象中进行展示;所以对于这个新生成的内容,我们需要用一个新的对象去接受;所以也是需要新创建一个entity去接收;所以这个时候创建的对象属性值是需要包含我们联表查询中需要查询出来的字段内容;

resultMap还可以把结果绑定到有层级关系的类属性上

package com.cmj.entity;

public class TeacherDept3 {
	private Teacher teacher;
	private Dept dept;
	//生成对应get、set方法。。。。。。
	
}
<!-- 联表查询3 -->

	<resultMap type="teacherDept3" id="teacherDept3">
		<result property="teacher.id" column="id" />
		<result property="teacher.name" column="tname" />
		<result property="dept.name" column="dname" />
		<result property="teacher.passWord" column="pass_word" />

	</resultMap>
	<select id="selectTeacherDept3" resultMap="teacherDept3">
		SELECT
		t.id,
		t.`name`
		tname,
		t.pass_word,
		d.`name` dname
		FROM
		teacher t
		LEFT JOIN dept d ON
		t.dept_id = d.id
		WHERE
		t.id = #{id}

	</select>

注意:resulMap中进行映射的id为图中圈出部分,这两个必须一致,才可以进行相匹配

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值