暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

​resultMap的使用

陌淮缘 2017-08-01
332

resultMap的使用

resultMap:用来描述如何将结果集映射到Java对象,特别是当数据库字段名与对象属性名不一致的使用,就需要做映射。

resultMap中存在很多的子元素:

"constructor":类在实例化时,用来注入结果到构造方法中。

"idArg":ID参数,标记结果作为ID,可以帮助提高整体的效率。

"arg":注入到构造方法的一个不同结果。

"id":这个id,类似于数据库的主键,能够帮助提高整体的效率

"result":即结果字段,其中包括Java对象的属性值,和数据库列名

"association":复杂类型的结果关联,结果映射能够关联自身,或者关联另一个结果集

"collection":复杂类型的集合,结果映射自身,或者映射结果集

"discriminator":使用结果值来决定使用哪个结果映射

"case":基于某些值的结果映射。嵌入结果映射,这种情形也映射到它本身,因此,能够包含相同的元素,或者参照一个外部的结果映射。

对于resultMap标签,上文的基础用法中我们已经介绍了他的属性含义。但,在此之外,还有一个属性值为:

“autoMapping”:如果出现此配置,Mybatis将会启用或者禁用自动匹配resultMap的功能,这个属性将会在全局范围内覆盖自动匹配机制。默认情况下是没有这个配置的,因此,如果需要,请保持慎重。

示例:

<resultMap id="detailedBlogResultMap" type="Blog">

  <constructor>

    <idArg column="blog_id" javaType="int"/>

  </constructor>

  <result property="title" column="blog_title"/>

  <association property="author" javaType="Author">

    <id property="id" column="author_id"/>

    <result property="username" column="author_username"/>

    <result property="password" column="author_password"/>

    <result property="email" column="author_email"/>

    <result property="bio" column="author_bio"/>

    <result property="favouriteSection" column="author_favourite_section"/>

  </association>

  <collection property="posts" ofType="Post">

    <id property="id" column="post_id"/>

    <result property="subject" column="post_subject"/>

    <association property="author" javaType="Author"/>

    <collection property="comments" ofType="Comment">

      <id property="id" column="comment_id"/>

    </collection>

    <collection property="tags" ofType="Tag" >

      <id property="id" column="tag_id"/>

    </collection>

    <discriminator javaType="int" column="draft">

      <case value="1" resultType="DraftPost"/>

    </discriminator>

  </collection>

</resultMap>


文章转载自陌淮缘,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论