resultMap使用案例:
1.CustomObjec对象的定义:
publicclassCustomObject{privateInteger cid;privateString cname;privateString pwd;
2.数据库 User表 中的列名
id、name、pwd
可以看出,用来接收数据的CustomObject对象 和User表 中的列名和对象名不一一对应。
如果要用resultType,数据库User表会把数据传递给CustomObject对象中与列名相同的的属性名。这样只有对象中的pwd属性能正确接收User表中的pwd列的值
此时就需要用到resultMap,建立CustomObject 对象 与User表的各列 的一一对应关系。
3. dao接口方法:
CustomObjectselectById2(@Param("stuid")Integer id);
4. mapper文件内的 sql语句 及 resultMap定义语句:
<!-- 定义resultMap
id:给resultMap的映射关系自定义一个名称,是唯一值
type:填java类型的全限定名称--><resultMapid="customMap"type="com.gys.vo.CustomObject"><!-- 定义列名和属性名的对应关系--><!-- 主键列使用id标签--><idcolumn="id"property="cid"/><!-- 非主键列使用result标签--><resultcolumn="name"property="cname"/><!-- 列名和属性名相同则不用再定义--></resultMap><!-- 使用resultMap属性来制定映射关系--><selectid="selectById2"resultMap="customMap">
select * from User where id=#{stuid}</select>
作用:
把User表主键列名id 对应CustomObject对象的属性 cid
把User表非主键列名name 对应CustomObject对象的属性 cname
由于User表非主键列名pwd 与CustomObject对象的属性 pwd 已经是对应关系,所以不需要再定义
select标签,使用resultMap属性,id的值为自定义的 resultMap 的 id 例如上面定义的customMap,表明在此标签中执行 id 为 customMap 的 resultMap 所定义的映射关系
5. 测试:
// 1.使用工具类@TestpublicvoidtestSelectById2(){SqlSession session=MyBatisUtil.getSqlSession();StudentDao dao= session.getMapper(StudentDao.class);CustomObject cstudent= dao.selectById2(3);// 传入参数 id=3System.out.println("student = "+ cstudent);
session.close();}
6. 结果:
student = CustomObject{cid=3,cname=‘李四3’, pwd=‘lisi3’}
7. 日志:
== Preparing: select * from User where id=?
== Parameters: 3(Integer)
== Columns: id, name, pwd
== Row: 3, 李四3, lisi3
== Total: 1
比较:
不使用 resultMap定义映射关系,而是直接使用resultType指定数据接收对象结果:
1. 只需要修改mapper文件内的 sql语句,其他不变:
<!-- 直接使用resulttype--><selectid="selectById2"resultType="com.gys.vo.CustomObject">
select * from User where id=#{stuid}</select>
2.结果:
student = CustomObject{cid=null, cname=‘null’, pwd=‘lisi3’}
3.日志:
== Preparing: select * from User where id=?
== Parameters: 3(Integer)
== Columns: id, name, pwd
== Row: 3, 李四3, lisi3
== Total: 1
通过两者的日志对比,可以知道,都获取到了完整信息。
使用resultMap的方法,建立映射关系,可以给对象的三个属性都接收数据成功
使用resultType的方法,没有建立映射关系,只有一个原先就存在对应关系的属性pwd接收数据成功