mybatis 的 resultMap 的使用
2017-05-06 22:15
267 查看
需求:数据库查询出来的字段名与pojo的属性名不一样
自定义映射关系
在Mapper.xml中配置
<!--
定义resultMap,将数据库查询出来的数据与pojo进行一个对应映射关系
type:最终映射的java对象
id:resultMap的唯一标识
-->
<resultMap type="user" id="userResultMap">
<!--
column:sql查询字段名
property:pojo的属性名
id标签:查询结果集的唯一标识 ,一般是主键,也可以是唯一标识
result标签:普通列
-->
<id column="id_" property="id"/>
<result column="username_" property="username"/>
</resultMap>
然后将上面的resultMap中id属性的值添加到statement中resultMap的位置
这样就可以自定义映射关系了
resultType和resultMap的区别
resultType:sql查询结果集使用resultType映射,要求sql查询字段名和pojo的属性名一致,才能映射成功。
resultMap: 如果sql查询结果集的字段名和pojo的属性名不一致,使用resultMap将sql查询字段名和pojo的属性作一个对应关系
,首先需要定义resultMap,最终要使用pojo作为结果集映射对象。
建议:一般情况下建议使用resultType,因为简单方便。
针对一对多查询或要使用延迟加载
,必须使用resultMap。
自定义映射关系
在Mapper.xml中配置
<!--
定义resultMap,将数据库查询出来的数据与pojo进行一个对应映射关系
type:最终映射的java对象
id:resultMap的唯一标识
-->
<resultMap type="user" id="userResultMap">
<!--
column:sql查询字段名
property:pojo的属性名
id标签:查询结果集的唯一标识 ,一般是主键,也可以是唯一标识
result标签:普通列
-->
<id column="id_" property="id"/>
<result column="username_" property="username"/>
</resultMap>
然后将上面的resultMap中id属性的值添加到statement中resultMap的位置
这样就可以自定义映射关系了
<select id="findUserList" resultMap="userResultMap"> SELECT id id_,username username_ FROM USER </select>
resultType和resultMap的区别
resultType:sql查询结果集使用resultType映射,要求sql查询字段名和pojo的属性名一致,才能映射成功。
resultMap: 如果sql查询结果集的字段名和pojo的属性名不一致,使用resultMap将sql查询字段名和pojo的属性作一个对应关系
,首先需要定义resultMap,最终要使用pojo作为结果集映射对象。
建议:一般情况下建议使用resultType,因为简单方便。
针对一对多查询或要使用延迟加载
,必须使用resultMap。
相关文章推荐
- 03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma
- 【Mybatis】表关联和resultMap的使用
- 关于mybatis扫描所有namespace时报错,最终原因是resultMap不能使用(我的错误记录)
- MyBatis Review——使用resultType和resultMap实现一对一查询
- 使用mybatis_generatoer工具后出现Result Maps collection already contains value for BaseResultMap
- Mybatis 里面ResultMap的使用情况
- Mybatis学习记录(四)----resultMap的使用
- mybatis 使用resultMap实现数据库的操作
- Mybatis的ResultMap的使用(转)
- Mybatis的ResultMap的使用
- MyBatis数据持久化(六)resultMap使用
- MyBatis 之ResultMap 使用介绍
- mybatis使用association的resultMap方式进行映射少数据问题
- Mybatis的ResultMap的使用
- 03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma
- MyBatis数据持久化(六)resultMap使用
- MyBatis数据持久化(六)resultMap使用
- MyBatis Review——使用resultType和resultMap实现一对一查询
- MyBatis 3.3.1 在resultMap中使用association但是没有指定id时的结果集bug