resultMap使用方法
resultMap的使用方法
resultMap使用案例:
1.CustomObjec对象的定义:
public class CustomObject {
private Integer cid;
private String cname;
private String pwd;
2.数据库 User表 中的列名
id、name、pwd
可以看出,用来接收数据的CustomObject对象 和 User表 中的列名和对象名不一一对应。
如果要用resultType,数据库User表会把 数据传递给 CustomObject对象中与列名相同的的属性名。这样只有对象中的pwd属性能正确接收User表中的pwd列的值
此时就需要用到resultMap,建立 CustomObject 对象 与 User表的各列 的 一一对应关系。
3. dao接口方法:
CustomObject selectById2(@Param("stuid") Integer id);
4. mapper文件内的 sql语句 及 resultMap定义语句:
<!-- 定义resultMap
id:给resultMap的映射关系自定义一个名称,是唯一值
type:填java类型的全限定名称-->
<resultMap id="customMap" type="com.gys.vo.CustomObject">
<!-- 定义列名和属性名的对应关系-->
<!-- 主键列使用id标签-->
<id column="id" property="cid"/>
<!-- 非主键列使用result标签-->
<result column="name" property="cname"/>
<!-- 列名和属性名相同则不用再定义-->
</resultMap>
<!-- 使用resultMap属性来制定映射关系-->
<select id="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.使用工具类
@Test
public void testSelectById2(){
SqlSession session = MyBatisUtil.getSqlSession();
StudentDao dao = session.getMapper(StudentDao.class);
CustomObject cstudent = dao.selectById2(3); // 传入参数 id=3
System.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-->
<select id="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接收数据成功
更多推荐
所有评论(0)