重学Mybatis从入门到源码之六---解决属性名和字段名不一致的问题

如果数据库中的字段名和代码中的属性名不一致,这很容易就不一致,因为代码中一般都是驼峰,数据库里面可能会有下划线。

1. 给字段名起别名:

<select id="selectUsers" resultType="User">
  select
    user_id             as "id",
    user_name           as "userName",
    hashed_password     as "hashedPassword"
  from some_table
  where id = #{id}
</select>

2. 使用resultMap

定义一个resultMap:

<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
</resultMap> 

使用这个result Map:

<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>

resultMap也不是要将所有的字段名都做一个映射,只写一下不一样的字段也是可以的。

原文地址:https://www.cnblogs.com/yunyunde/p/13826534.html