Mybatis解決屬性名和字段名不一致的問題

新建一個項目,拷貝之前的,測試實體類字段不一致的情況,如:數據庫中的字段是username,實體類的字段是user,在執行查詢的時候就會返回user=null

解決辦法:

  • 起別名
<select id="getUserById" resultType="com.superman.pojo.User" parameterType="int">
    select id,birthday,sex,address,username as user from mybatis.user where id=#{id};
</select>
  • 使用resulrMap
實體類中的屬性  id username password
數據庫中的字段  id name     password 

<!--結果集映射-->
<!--id就是resultMap使用的id,type就是返回的實體類-->
<resultMap id="UserMap" type="User">
    <!--column就是數據庫中對應的字段,property就是實體類中的屬性-->
    <!--如果只是要對應實體類的一個屬性與數據庫中的一個字段,只需要寫出需要對應的那一個即可。-->
    <result column="id" property="id"/>
    <result column="username" property="name"/>
    <result column="birthday" property="birthday"/>
    <result column="address" property="address"/>
    <result column="sex" property="sex"/>
</resultMap>
  • resuleMap元素是mybatis中最重要最強大的元素
  • resultmap的設計思想是,對於簡單的語句根本不需要配置顯式的結果映射,而對於複雜一點的語句- 只需要描述他們的關係就好了
  • resultmap最優秀的地方在於,雖然你已經對它相當瞭解了,但是根本就不需要顯式的用到
  • 如果世界總是這麼簡單就好了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章