输出映射
接下来说说有关Mapper.xml配置文件中查询标签中关于返回值类型resultType与resultMap的一些内容
1.resultType
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。
只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
1.1输出简单类型
1.1.1需求
用户信息的综合查询列表总数,通过查询总数和上边用户综合查询列表才可以实现分页。
1.1.2mapper.xml
1.1.3mapper.java
1.1.4测试代码
测试结果:
总数为:2
输出日志:
1.1.5小结
查询出来的结果集只有一行且一列,可以使用简单类型进行输出映射。(输出简单类型的要求)
1.2输出pojo对象和pojo列表
不管是输出的pojo单个对象还是一个列表(list中包括pojo),在mapper.xml中resultType指定的类型是一样的。
在mapper.java指定的方法返回值类型不一样:
(1)输出单个pojo对象,方法返回值是单个对象类型
(2)输出pojo对象list,方法返回值是List<Pojo>
生成的动态代理对象中是根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList (返回集合对象调用 ).
(3)输出hashmap
输出pojo对象可以改用hashmap输出类型,将输出的字段名称作为map的key,value为字段值。如果是集合,那就是list里面套了HashMap。
2.resultMap
mybatis中使用resultMap完成高级输出结果映射。
2.1resultMap使用方法
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。
下面来进行实验,实验需求
2.2将下边的sql使用User完成映射
SELECT id id_,username username_ FROM USER WHERE id=#{value}
User类中属性名和上边查询列名不一致。
resultMap使用方法:(一下属性均定义在Mapper.xml映射文件中)
(1)定义resultMap
(2)使用resultMap作为statement的输出映射类型
测试结果:
张三
小结
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
接下来说说有关Mapper.xml配置文件中查询标签中关于返回值类型resultType与resultMap的一些内容
1.resultType
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。
只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
1.1输出简单类型
1.1.1需求
用户信息的综合查询列表总数,通过查询总数和上边用户综合查询列表才可以实现分页。
1.1.2mapper.xml
1.1.3mapper.java
1.1.4测试代码
测试结果:
总数为:2
输出日志:
1.1.5小结
查询出来的结果集只有一行且一列,可以使用简单类型进行输出映射。(输出简单类型的要求)
1.2输出pojo对象和pojo列表
不管是输出的pojo单个对象还是一个列表(list中包括pojo),在mapper.xml中resultType指定的类型是一样的。
在mapper.java指定的方法返回值类型不一样:
(1)输出单个pojo对象,方法返回值是单个对象类型
(2)输出pojo对象list,方法返回值是List<Pojo>
生成的动态代理对象中是根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList (返回集合对象调用 ).
(3)输出hashmap
输出pojo对象可以改用hashmap输出类型,将输出的字段名称作为map的key,value为字段值。如果是集合,那就是list里面套了HashMap。
2.resultMap
mybatis中使用resultMap完成高级输出结果映射。
2.1resultMap使用方法
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。
下面来进行实验,实验需求
2.2将下边的sql使用User完成映射
SELECT id id_,username username_ FROM USER WHERE id=#{value}
User类中属性名和上边查询列名不一致。
resultMap使用方法:(一下属性均定义在Mapper.xml映射文件中)
(1)定义resultMap
(2)使用resultMap作为statement的输出映射类型
(3)mapper接口类中添加相应方法
测试:
测试结果:
张三
输出日志:
小结
使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。