在mapper.xml里返回值不止有一个resultType还有一个resultMap,这里介绍一下用法
1、resultMap属性的使用:
问题描述:
当数据库的属性名和pojo不一致的时候,会出现不匹配从而输出为null的情况,这个时候就会用到 resultMap
具体点:数据库里面是user_id,pojo里面是userId,这就出事了,这个时候的userId不能识别全为null
解决方法1:
直接在SQL语句user_id后面加上userId的别名
<select id="seclectAllFromOrder" resultType="order">
SELECT
`id`,
<!-- 加上别名 -->
`user_id` `userId`,
`number`,
`createtime`,
`note`
FROM
`mybatis`.`order`
</select>
解决方法2:设置resultMap
在mapper.xml里面设置resultMap并引用:
<resultMap type="order" id="order_map">
设置主键映射
<id property="id" column="id" />
设置其它键的映射(这里的userId映射了user_id)
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
</resultMap>
使用resultMap,引用一下上面定义的resultMap
<select id="seclectAllFromOrder" resultMap="order_map">
SELECT
`id`,
`user_id`,
`number`,
`createtime`,
`note`
FROM
`mybatis`.`order`
</select>
这个时候就能正常输出了
resultMap还有一个很重要的应用就是在多表关联查询的时候关联表之间的映射,核心配置如下
一对一关联,一张订单只有一个用户,一种是订单的pojo加上用户的属性,另一种就是resultMap,将用户关联上
<association property="绑定的用户属性" javaType="属性的数据类型,支持别名" ></association>
一对多关联,一个用户有多个订单,需要在用户pojo中加一个订单集合
<collection property="绑定的用户属性" ofType="属性的数据类型,支持别名"></collection>
关联之后还是像之前一样,把属性映射一下(这个时候的主键要分清,最好用别名):
设置主键映射
<id property="id" column="id" />
设置其它键的映射(这里的userId映射了user_id)
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />