mybatis中联合查询的返回结果集

本文主要是转载。

其中踩过的坑,第一个是在联合的结果集中,其中column是sql的列名,后面的property是bean中的字段。

在联合查询中,如果出现重名的字段,必须用别名的方式,重命名。别名再映射到column上。

建议使用左连接,不要使用第一种注释掉的方法,实际操作中,丢数据,比如role的值为空的情况下,他会忽略掉。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.taotao.dao.AdminMapper">  
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache> 

<resultMap type="cn.taotao.bean.Admin" id="WithRoleResultMap">
      <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    
    <!-- 指定联合查询出的角色字段的封装 -->
    <association property="role" javaType="cn.taotao.bean.Role">
        <id column="role" property="id"/>
        <result column="rname" property="name"/>
        <result column="desc" property="desc"/>
    </association>
  </resultMap>
<select id="getAdmins" resultMap="WithRoleResultMap">
<!-- select a.id,a.name,a.password,a.email,a.role,r.desc,r.name bname  from tbl_admin a,tbl_role r  where a.role=r.id order by a.id asc -->
select a.id ,a.name,a.password,a.email,a.role,r.desc,r.name rname from tbl_admin a left join tbl_role r on a.role =  r.id order by a.id asc
</select>
</mapper>

resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。

resultMap包含的元素:

复制代码
<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultMap id="唯一的标识" type="映射的pojo对象">
  <id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
  <result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
  <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
    <id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
    <result  column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
  </association>
  <!-- 集合中的property须为oftype定义的pojo对象的属性-->
  <collection property="pojo的集合属性" ofType="集合中的pojo对象">
    <id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
    <result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
  </collection>
</resultMap>
复制代码

如果collection标签是使用嵌套查询,格式如下:

 <collection column="传递给嵌套查询语句的字段参数" property="pojo对象中集合属性" ofType="集合属性中的pojo对象" select="嵌套的查询语句" > 
 </collection>

注意:<collection>标签中的column:要传递给select查询语句的参数,如果传递多个参数,格式为column= ” {参数名1=表字段1,参数名2=表字段2} ;

原文地址:https://www.cnblogs.com/sdgtxuyong/p/12011793.html