继续上一篇的内容,我们继续来用补充resultMap来映射类型转换与字段名识别。
resultMap可以实现2个功能:
1.类型转换
2.属性-字段的映射关系
应用:
1、如果 类中的属性 和 表中的字段 类型 能够合理识别(String - varchar2),则使用 resultType,否则使用resultMap。
2、如果 类中的属性名 和 表中的字段名 能够合理识别 (Name - name),则使用resultMap,否则使用 resultMap
代码示例:
在mapper.xml中
<!-- type是映射的实际类型,id指定该resultMap的名字,其他地方通过该id来使用该映射 -->
<resultMap type="person" id="personMap">
<!-- property="类中属性名(大小写一致)" column="表中字段名(大小写可不同)" ,这两个属性实现了 类属性名与字段名匹配,即使类属性名和表字段名不一致,也能在逻辑上使之处理时一一对应起来-->
<!-- javaType="" jdbcType="" 使之类型可以正确识别转化 -->
<!-- typeHandler="" 指定 类型转换器 -->
<!-- 主键 -->
<id property="id" column="id"/>
<!-- 非主键 -->
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="sex" column="sex" javaType="boolean" jdbcType="INTEGER" typeHandler="org.ltx.converter.BooleanAndIntConverter"/>
</resultMap>
<!-- resultMap="resultMap的id值" -->
<select id="queryPersonById" parameterType="int" resultMap="personMap">
select * from person where id=#{id}
</select>
<!-- 转换器的增加-->
<insert id="addPerson" parameterType="person">
insert into person(id,name,age,sex) values(#{id},#{name},#{age},#{sex,javaType=boolean,jdbcType=INTEGER })
</insert>