码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-27 13:04:29      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:


      例如:

                 查询订单信息,关联查询创建订单的用户信息。


     查询语句:

            

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无法实现延迟加载。




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

标签:

原文地址:http://blog.csdn.net/lhc1105/article/details/51480528

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!