`
wx1568847608
  • 浏览: 12240 次
文章分类
社区版块
存档分类
最新评论

Mapper.xml

 
阅读更多

<mapper namespace="xxx.UserMapper">
<--命名空间的值不能随便取,必须和已经创建的UserMapper接口路径一致 -->
//这两段代码就是resultMapper使用核心,resultMap 中的type代表最终的映射对象,也就是我们定义的那么工具类,后面跟着的id值是可以随便命名的,一般这样命名userRM(RM就是resultMapper),他的作用作为resultMapper的唯一标识,<result column>中的column是SQL查询的列名,如果列有别名,那么此处的值应该写别名,property后面的属性值为我们工具类中所对应的值。这里要指出的是,只有数据库列名和工具类中的属性名对应上才能查到数据。
<resultMap type="XXX.User" id="a">
    <id column="id_" property="id"/>
    <result column="username_" property="username"/>
    <result column="sex_" property="sex"/>
</resultMap>

//<select id="" parameterType="" resultMap="">这三个属性很好理解,这里就是实现了我们使用代理时需要遵守的规范,id名和我们接口的方法名相同,parameterType值为接口中的传入数据类型,resultMap可以理解为返回的数据类型,它的值和我们上面<resultMap type="" id="">中的id值相对应,最后就是纯sql语句的查询了,没有返回值就不用制定了。
<select id="findUserByIdResultMap" parameterType="int" resultMap="a">
SELECT id id_,username username_,sex sex_ FROM USER WHERE id = #{id}
</select>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 在sql映射文件中,Mybatis中namespace终于派上用场,它使得映射文件和接口之间的绑定变的非常自然。 在iBatis中namespace不是必须的 -->
<mapper namespace="com.test.dao.NarCodeMapper">

    <resultMap id="BaseResultMap" type="narCode">
           <!-- property是实体类属性,column是表列名 -->
        <id property="id" column="id" jdbcType="VARCHAR" />
        <result property="cnt" column="cnt"  jdbcType="VARCHAR" />
        <result property="parentid" column="parentid"jdbcType="VARCHAR" />
        <result property="dlevel" column="dlevel" jdbcType="VARCHAR" />
    </resultMap>
    <!-- 返回单个实例-->
    <select id="getNarCode" parameterType="java.lang.String"
        resultType="narCode">
        select a.id,a.cnt,a.parentid,a.dlevel from nar_code a
        where a.id = #{id,jdbcType=VARCHAR}
    </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>
</mapper>

1.当提供的返回类型属性是resultType时,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis会自动把对应的值赋给resultType所指定对象的属性。

2.当提供的返回类型是resultMap时,因为Map不能很好表示领域模型,就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

转载于:https://my.oschina.net/u/3043570/blog/2243875

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics