天天看點

MyBatis學習筆記——第四部分 解決屬性名和字段名不一緻的問題(ResultMap)1. 問題出現2. resultMap結果集映射

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

  • 1. 問題出現
  • 2. resultMap結果集映射

1. 問題出現

資料庫中的字段

MyBatis學習筆記——第四部分 解決屬性名和字段名不一緻的問題(ResultMap)1. 問題出現2. resultMap結果集映射

建立項目,修改實體類,使字段不一緻

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

測試出現問題

MyBatis學習筆記——第四部分 解決屬性名和字段名不一緻的問題(ResultMap)1. 問題出現2. resultMap結果集映射

解決方法:

  • 起别名

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 的優秀之處——你完全可以不用顯式地配置它們。