4.Mybatis的ResultMap

穿精又带淫゛_ 提交于 2020-02-12 01:53:55

一.ResultMap

  • 要解决的问题:属性名和字段名不一致

1.案例:查询为null的问题

数据库:

 

实体类:

结果:password='null'

2.解决方案

(1)方案一:为列名指定别名 , 别名和java实体类的属性名一致 . pwd as password 

1 <!--根据ID查询用户-->
2 <select id="getUserById" parameterType="int" resultType="User">
3   select id,name,pwd as password from mybatis.user where id=#{id}
4 </select>

(2)方案二:使用结果集映射->ResultMap (推荐使用)

  • 添加一个resultMap标签,配置column为数据库中列名,property为实体类中属性名的对应关系,相同的可省略
  • 将resultType改为resultMap,并将值赋为UserMap
 1 <resultMap id="UserMap" type="User">
 2     <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
 3     <!--<id column="id" property="id"/>-->
 4     <!--<result column="name" property="name"/>-->
 5     <result column="pwd" property="password"/>
 6 </resultMap>
 7 
 8 <!--根据ID查询用户-->
 9 <select id="getUserById" parameterType="int" resultMap="UserMap">
10   select * from mybatis.user where id=#{id}
11 </select>

3.resultMap中还有大量的属性之后再研究

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!