您的位置:首页 > 其它

MyBatis Review——使用resultType和resultMap实现一对一查询

2016-05-23 13:15 585 查看
      例如:
                 查询订单信息,关联查询创建订单的用户信息。

     查询语句:
             SELECT
orders.*, USER .username ,USER .sex,
USER .address
FROM
orders,
USER
WHERE
orders.user_id = USER .id  

    查询结果:

    1,使用resultType接受输出结果

                 用户信息:

                        

             订单信息:

                         

          用于接收结果的pojo:

               

       为了将查询结果映射到pojo中,pojo必须包括所有查询列名。在原始orders对象不能接受所有查询字段的时候,定义OrdersCustom来进行扩展字段。

        之后将resutlType在xml中配置为我们定义的新的pojo类:
   <!-- 查询订单关联查询用户 -->
<select id="findOrdersUser" resultType="cn.itcast.mybatis.po.OrdersCustom">
SELECT
orders.*, USER
.username ,USER .sex,
USER .address
FROM
orders,
USER
WHERE
orders.user_id =
USER .id
</select>

   2,使用resultMap接受返回结果

               使用resultMap将查询结果中的订单信息映射到Orders对象中,在orders类中添加User属性,将关联查询出来的用户信息映射到orders对象中的user属性中。

        

           配置resultMap:

<!-- 定义订单查询关联用户的resultMap -->
<resultMap type="cn.itcast.mybatis.po.Orders" id="OrdersUserResultMap">
<!-- 配置映射的订单信息 -->
<id column="id" property="id"/><!-- 订单信息的唯一标识 --><!-- 如果有多个列,组成唯一标识,配置多个id -->
<result column="user_id" property="userId" />
<result column="number" property="number" />
<result column="createtime" property="createtime" />
<result column="note" property="note" />

<!-- 配置映射的关联的用户信息 -->
<!-- association:用于映射关联查询单个对象的信息 property:将关联查询的用户信息映射到orders的那个属性中 -->
<association property="user" javaType="cn.itcast.mybatis.po.User">
<!-- 关联查询的用户的唯一标识 column:指定唯一标识用户信息的列 -->
<id column="user_id" property="id" />
<result column="username" property="username" />
<result column="sex" property="sex" />
<result column="address" property="address" />
</association>

</resultMap>

   xml中输出结果配置:

  <!-- 查询订单关联查询用户 :使用resultMap -->
<select id="findOrdersUserResultMap" resultMap="OrdersUserResultMap">
SELECT
orders.*, USER
.username ,USER .sex,
USER .address
FROM
orders,
USER
WHERE
orders.user_id =
USER .id
</select>

   小结:      
         实现一对一查询,使用上面两种方式作为输出:
        resultType:使用resultType实现较为简单,如果pojo中没有包括查询出来的列名,需要增加列名对应的属性,即可完成映射。如果没有查询结果的特殊要求建议使用resultType。         resultMap:需要单独定义resultMap,实现有点麻烦,如果对查询结果有特殊的要求,使用resultMap可以完成将关联查询映射pojo的属性中。         结果上的区别:resultMap可以实现延迟加载,resultType无法实现延迟加载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: