Mybatis-ResultMap
1 基本使用
解决的问题 属性名与字段名不一致
<!--
resultMap 用来自定义结果集和实体类的映射
属性:
id 相当于这个resultMap的唯一标识
type 用来指定映射到哪个实体类
id标签 用来指定主键列的映射规则
属性:
property 要映射的属性名
column 对应的列名
result标签 用来指定普通列的映射规则
属性:
property 要映射的属性名
column 对应的列名
-->
<resultMap id="orderMap" type="com.lzy.entities.Order" >
<id column="id" property="id"></id>
<result column="createtime" property="createtime"></result>
<result column="price" property="price"></result>
<result column="remark" property="remark"></result>
<result column="user_id" property="userId"></result>
</resultMap>
<!--使用我们自定义的映射规则-->
<select id="findAll" resultMap="orderMap">
SELECT id,createtime,price,remark,user_id FROM ORDERS
</select>
发现,数据库中字段名为pwd,而实体类中变量名为password,导致查询password为空
1.1解决方法
1.1.1为列名指定别名
<select id="selectUserById" resultType="User">
select id , name , pwd as password from user where id = #{id}
</select>
1.1.2 使用结果集映射->ResultMap 【推荐】
我们定义resultMap时默认情况下自动映射是开启状态的。也就是如果结果集的列名和我们的属性名相同是会自动映射的我们只需要写特殊情况的映射关系即可。
<resultMap id="orderMap" type="com.lzy.entities.Order" >
<result column="user_id" property="userId"></result>
</resultMap>
<!--使用我们自定义的映射规则-->
<select id="findAll" resultMap="orderMap">
SELECT id,createtime,price,remark,user_id FROM ORDERS
</select>
可以选择关闭自动映射
<resultMap id="orderMap" type="com.lzy.entities.Order" autoMapping="false">
<id column="id" property="id"></id>
<result column="createtime" property="createtime"></result>
<result column="price" property="price"></result>
<result column="remark" property="remark"></result>
<result column="user_id" property="userId"></result>
</resultMap>
继承映射关系
<!--定义个父映射,供其他resultMap继承-->
<resultMap id="baseOrderMap" type="com.lzy.entities.Order" >
<id column="id" property="id"></id>
<result column="createtime" property="createtime"></result>
<result column="price" property="price"></result>
<result column="remark" property="remark"></result>
</resultMap>
<!--继承baseOrderMap,然后只需要写自己特有的映射关系即可-->
<resultMap id="orderMap" type="com.lzy.entities.Order" autoMapping="false" extends="baseOrderMap">
<result column="user_id" property="userId"></result>
</resultMap>
使用结果集映射
<resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
</select>