您的位置:首页 > 其它

Mybatis 连表查询,返回结果封装为Map

2017-12-08 08:49 691 查看
在SSM的项目中,数据的持久化操作都使用Mybatis实现,Mybatis抢的Mapper配置文件,可以让我们灵活得编写SQL语句。在我们需要进行连表查询时,需要传入的参数可能不止一个,这个时候我们将参数封装至一个自定义的对象,或者存储到一个Map之中,查询结果同样可以封装至一个自定义的对象或者Map。 

以下对两种方法分别进行说明。 

一:参数parameterType为自定义的对象,resultMap为与对象属性相对应的的ID
<resultMap id="BaseResultMap" type="com.example.domain.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, password, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="com.example.domain.User" >
select
<include refid="Base_Column_List" />
from user_t
where id = #{id,jdbcType=INTEGER}
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

二:参数parameterType为map,resultMap为HashMap类型
<resultMap id="loopSpeedResult"   type="HashMap">
<result column="cab_name" property="cabName"/>
<result column="speed" property="speed" />
</resultMap>
<select id="selectLoopSpeed"  parameterType="java.util.Map"  resultMap="loopSpeedResult">
SELECT B.cab_name as cab_name, round(avg(speed),2) as speed
FROM table1 as A, table2 as B
Where left(right(B.unit_name,3),2) = '__'
and (B.lon between #{minLon}  and #{maxLon} )
and (B.lat between #{minLat}  and #{maxLat} )
and stamp <![CDATA[ >= ]]>  #{beginTime,jdbcType=TIMESTAMP} and stamp <![CDATA[ <= ]]>  #{endTime,jdbcType=TIMESTAMP}
and A.lid = B.id
group by B.id
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

在调用时候,先把参数存储到Map中,注意key值就是 mapper.xml中参数的名字,返回结果map中的key值就是resultMap设置的property
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: