zoukankan      html  css  js  c++  java
  • 【MyBatis】学习笔记006--resultMap简单结果映射

    resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

    简单映射语句的示例,它们没有显式指定 resultMap。比如:

    <select id="selectUsers" resultType="map">
      select id, username, hashedPassword
      from some_table
      where id = #{id}
    </select>

    上述语句只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定。虽然在大部分情况下都够用,但是 HashMap 并不是一个很好的领域模型。我们的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为领域模型。MyBatis 对两者都提供了支持。看看下面这个 JavaBean:

    public class User {
      private int id;
      private String username;
      private String hashedPassword;
    }

    基于 JavaBean 的规范,上面这个类有 3 个属性:id,username 和 hashedPassword。这些属性会对应到 select 语句中的列名。

    这样的一个 JavaBean 可以被映射到 ResultSet,就像映射到 HashMap 一样简单。

    <select id="selectUsers" resultType="com.someapp.model.User">
      select id, username, hashedPassword
      from some_table
      where id = #{id}
    </select>

    当数据库字段名与JavaBean属性名不一致时呢?显时resultMap是你最好的选择(id标签字段为主键,column为数据库字段,property为JavaBean属性):

    <resultMap id="userResultMap" type="User">
      <id property="id" column="user_id" />
      <result property="username" column="user_name"/>
      <result property="password" column="hashed_password"/>
    </resultMap>
    <select id="selectUsers" resultMap="userResultMap">
      select user_id, user_name, hashed_password
      from some_table
      where id = #{id}
    </select>
  • 相关阅读:
    topsort模板,poj 2585
    CUG2012年暑期ACM训练赛(单人赛)
    第一个QT, "hello linux"
    AOE网络,最长路关键路径的学习
    种类位置信息:geometry
    标准对话框:StandardDialogs
    最近整理的模板
    单调队列的学习
    118 ZOJ Monthly, July 2012
    离散化 + unique + lower_bound的学习,hdu4325
  • 原文地址:https://www.cnblogs.com/AirCL/p/14334572.html
Copyright © 2011-2022 走看看