resultType和resultMap只能有一個成立,resultType是直接表示返回類型的,而resultMap則是對外部ResultMap的引用,resultMap解決復雜查詢是的映射問題。比如:列名和對象屬性名不一致時可以使用resultMap來配置;還有查詢的對象中包含其他的對象等。
Xml配置文件:MyBatis-Configuration.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6 <!-- 類型別名只是為Java類型設置一個短的名稱。他只和xml配置有關,存在的意義僅用來減少類完全限定名的冗余 -->
7 <typeAliases>
8 <typeAlias alias="narCode" type="com.test.model.NarCode"/>
9 </typeAliases>
10 <!-- 程序中所用到sql映射文件都在這里列出,這些映射sql都被Mybatis管理 -->
11 <mappers>
12 <mapper resource="com/test/xml/NarCodeMapper.xml"/>
13 </mappers>
14 </configuration>
Xml映射文件配置:NarCodeMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
3 <!-- 在sql映射文件中,Mybatis中namespace終於派上用場,它使得映射文件和接口之間的綁定變的非常自然。 在iBatis中namespace不是必須的 -->
4 <mapper namespace="com.test.dao.NarCodeMapper">
5
6 <resultMap id="BaseResultMap" type="narCode">
<!-- property是實體類屬性,column是表列名 -->
7 <id property="id" column="id" jdbcType="VARCHAR" />
8 <result property="cnt" column="cnt" jdbcType="VARCHAR" />
9 <result property="parentid" column="parentid"jdbcType="VARCHAR" />
10 <result property="dlevel" column="dlevel" jdbcType="VARCHAR" />
11 </resultMap>
12 <!-- 返回單個實例-->
13 <select id="getNarCode" parameterType="java.lang.String"
14 resultType="narCode">
15 select a.id,a.cnt,a.parentid,a.dlevel from nar_code a 16 where a.id = #{id,jdbcType=VARCHAR} 17 </select>
<!-- resultType非常適合返回jdk的提供的類型 -->
<select id="getNarCodeCount"
resultType="java.lang.Integer">
select count(*) from nar_code a
</select>
<!-- 返回List集合-->
<select id="getNarCodeList" resultType="BaseResultMap">
select a.id,a.cnt,a.parentid,a.dlevel from nar_code a
</select>
18 </mapper>
MyBatis中關於resultType和resultMap的具體區別如下:
MyBatis中在查詢進行select映射的時候,返回類型可以用resultType,也可以用resultMap,resultType是直接表示返回類型的(對應着我們的model對象中的實體),而resultMap則是對外部ResultMap的引用(提前定義了db和model之間的隱射key-->value關系),但是resultType跟resultMap不能同時存在。
在MyBatis進行查詢映射時,其實查詢出來的每一個屬性都是放在一個對應的Map里面的,其中鍵是列名,值則是其對應的值。
1.當提供的返回類型屬性是resultType時,MyBatis會將Map里面的鍵值對取出賦給resultType所指定的對象對應的屬性。所以其實MyBatis的每一個查詢映射的返回類型都是ResultMap,只是當提供的返回類型屬性是resultType的時候,MyBatis會自動把對應的值賦給resultType所指定對象的屬性。
2.當提供的返回類型是resultMap時,因為Map不能很好表示領域模型,就需要自己再進一步的把它轉化為對應的對象,這常常在復雜查詢中很有作用。