1. 程式人生 > 其它 >Mybatis入門(六) ResultMap對映結果集

Mybatis入門(六) ResultMap對映結果集

當我們查詢時,傳入的引數是一個物件時(parameterType="POJO具體類"),mybatis存在一個型別處理器(typeHandlers),會自動將資料庫的欄位和具體類中屬性進行匹配,當資料庫表格的欄位和具體類的屬性不一致時,如下圖,查詢出來的結果,pwd會對應為null,這時候就需要解決了。

解決辦法一,直接在sql語句中使用別名查詢,如下:該方法粗暴簡單

    <select id="getUserById" resultType="user" parameterType="int" >
        select id,`name`,passward as pwd
from school.user where id = #{id} </select>

解決方法二,使用ResultMap 結果集映照,即將查詢的結果先進行對映,在返回對應的型別,對應程式碼如下,其中select的標籤中,mark要對應resultMap中id的mark,表示使用上面的對映關係,type型別為返回物件,

    <resultMap id="mark" type="user">
        <result column="id" property="id"/>
        <result column="name" property="
name"/> <result column="passward" property="pwd"/> </resultMap> <select id="getUserById" resultMap="mark" parameterType="int" > select id,`name`,passward as pwd from school.user where id = #{id} </select>

column 表示從資料庫中查詢到的欄位或者別名
property 表示具體類的對應的屬性值