1. 程式人生 > >Mybatis 中 Mapper XML 檔案 的學習詳解(強烈推薦)

Mybatis 中 Mapper XML 檔案 的學習詳解(強烈推薦)

Auto-mapping

As you have already seen in the previous sections, in simple cases MyBatis can auto-map the results for you and in others you will need to build a result map. But as you will see in this section you can also mix both strategies. Let's have a deeper look at how auto-mapping works.

When auto-mapping results MyBatis will get the column name and look for a property with the same name ignoring case. That means that if a column named ID and property named id are found, MyBatis will set the id property with the ID column value.

Usually database columns are named using uppercase letters and underscores between words and java properties often follow the camelcase naming covention. To enable the auto-mapping between them set the setting mapUnderscoreToCamelCase to true.

Auto-mapping works even when there is an specific result map. When this happens, for each result map, all columns that are present in the ResultSet that have not a manual mapping will be auto-mapped, then manual mappings will be processed. In the following sample id and userName columns will be auto-mapped and hashed_password

 column will be mapped.

<selectid="selectUsers"parameterType="int"resultType="User">   select
    user_id             as "id",
    user_name           as "userName",
    hashed_password
  from some_table
  where id = #{id}</select>
<resultMapid="userResultMap"type="User"><resultproperty="password"column="hashed_password"/></resultMap>

There are three auto-mapping levels:

  • NONE - disables auto-mapping. Only manually mapped properties will be set.
  • PARTIAL - will auto-map results except those that have nested result mappings defined inside (joins).
  • FULL - auto-maps everything.

The default value is PARTIAL, and it is so for a reason. When FULL is used auto-mapping will be performed when processing join results and joins retrieve data of several different entities in the same row hence this may result in undesired mappings. To understand the risk have a look at the following sample:

<selectid="selectBlog"parameterType="int"resultMap="blogResult">   select
    B.id,
    B.title,
    A.username,
  from Blog B left outer join Author A on B.author_id = A.id
  where B.id = #{id}</select>
<resultMapid="blogResult"type="Blog"><associationproperty="author"javaType="Author"resultMap="authorResult"/></resultMap><resultMapid="authorResult"type="Author"><resultproperty="username"column="author_username"/></resultMap>

With this result map both Blog and Author will be auto-mapped. But note that Author has an idproperty and there is a column named id in the ResultSet so Author's id will be filled with Blog's id, and that is not what you were expecting. So use the FULL option with caution.