Mybatis笔记四:Mybatis中的resultType和resultMap查询操作实例详解

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不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

 

posted @ 2017-03-15 15:07  IT~任重而道远  阅读(17885)  评论(0编辑  收藏  举报