1. 程式人生 > 其它 >MyBatis學習筆記——第四部分 解決屬性名和欄位名不一致的問題(ResultMap)

MyBatis學習筆記——第四部分 解決屬性名和欄位名不一致的問題(ResultMap)

技術標籤:MyBatis學習筆記資料庫mybatisjavamysql

MyBatis學習筆記——第四部分 解決屬性名和欄位名不一致的問題(ResultMap)

1. 問題出現

資料庫中的欄位
在這裡插入圖片描述
新建專案,修改實體類,使欄位不一致

private int id;
private String name;
private String password;

測試出現問題
在這裡插入圖片描述
解決方法:

  • 起別名
select id,name,psd as password from mybatis.user where id=#{id}

2. resultMap結果集對映

<resultMap id="UserMap" type="com.zhang.pojo.User">
    <!--result column="id" property="id"/-->
    <!--result column="name" property="name"/-->
    <result column="psd" property="password"/>
</resultMap
>
<select id="getUserById" resultMap="UserMap"> select * from mybatis.user where id=#{id} </select>
  • resultMap 元素是 MyBatis 中最重要最強大的元素;
  • ResultMap 的設計思想是,對簡單的語句做到零配置,對於複雜一點的語句,只需要描述語句之間的關係就行了;
  • 這就是 ResultMap 的優秀之處——你完全可以不用顯式地配置它們。