Mybatis——resultMap

resultMap解釋:java

通常寫mybatis時,爲以下格式sql

<select id="selectUsers" resultType="com.someapp.model.User">
select id, username, hashedPassword
from some_table
where id = #{id}
</select>

以上格式要求咱們數據表和java類中的屬性名一致。 若是不一致,咱們也能夠用sql中的別名來進行匹配,以下緩存

<typeAlias type="com.someapp.model.User" alias="User"/>
//使用類型別名,下面就再也不須要輸入類的徹底限定名稱了。
<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>

resultMap就是來實現數據表和java類中屬性的匹配的問題的,上面咱們沒有直接調用它,但其實也是mybatis隱性的調用了resultMap才實現了映射。 下面咱們顯式的使用一下result,來看一下對映射處理過程。ps:這也是解決名稱不匹配的一種辦法mybatis

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

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

resultMap中的id和result基本相同,惟一不一樣是id 表示的結果將是對象的標識屬性,這會在比較對象實例時用到。 這樣能夠提升總體的性能,尤爲是緩存和嵌套結果映射(也就是聯合映射)的時候。app

相關文章
相關標籤/搜索