Mybatis的介绍以及使用:http://www.mybatis.org/mybatis-3/zh/index.html
resultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。
resultMap包含的元素:
如果collection标签是使用嵌套查询,格式如下:
注意:标签中的column:要传递给select查询语句的参数,如果传递多个参数,格式为column= ” {参数名1=表字段1,参数名2=表字段2} ;
以下以实例介绍resultMap的用法:
一、简单需求:一个商品的结果映射;
1、创建商品pojo对象:
public class TShopSku {
/**
* 主键ID
*/
private Long id;
/**
* 商品名
*/
private String skuName;
/**
* 分类ID
*/
private Long categoryId;
/**
* 主键ID
* @return ID
*/
public Long getId() {
return id;
}
/**
* 主键ID,
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 商品名
* @return SKU_NAME 商品名
*/
public String getSkuName() {
return skuName;
}
/**
* 商品名
* @param skuName 商品名
*/
public void setSkuName(String skuName) {
this.skuName = skuName == null ? null : skuName.trim();
}
/**
* 分类ID
* @return CATEGORY_ID 分类ID
*/
public Long getCategoryId() {
return categoryId;
}
/**
* 分类ID
* @param categoryId 分类ID
*/
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
对应的resultMap:
<resultMap id="BaseResultMap" type="com.meikai.shop.entity.TShopSku">
<id column="ID" jdbcType="BIGINT" property="id" />
<result column="SKU_NAME" jdbcType="VARCHAR" property="skuName" />
<result column="CATEGORY_ID" jdbcType="BIGINT" property="categoryId" />
二、商品pojo类添加属性集合:
一个商品会有一些属性,现在需要将查询出的商品属性添加到商品对象中,首先需要在原商品pojo类的基础上中添加属性的集合:
/**
* 属性集合
*/
private List attributes;
/**
* 获得属性集合
*/
public List<TShopAttribute> getAttributes() {
return attributes;
}
/**
* 设置属性集合
* @param attributes
*/
public void setAttributes(List<TShopAttribute> attributes) {
this.attributes = attributes;
}
将Collection标签添加到resultMap中,这里有两种方式:
1、嵌套结果:
对应的resultMap:
select s.ID,s.SKU_NAME,s.CATEGORY_ID,a.ID,a.ATTRIBUTE_NAME
from t_shop_sku s,t_shop_attribute a
where s.ID =a.SKU_ID and s.ID = #{id,jdbcType =BIGINT};
2、关联的嵌套查询(在collection中添加select属性):
商品结果集映射resultMap:
collection的select会执行下面的查询属性语句:
select a.ID,s.ATTRIBUTE_NAME
from t_shop_attribute a
where a.ID = #{skuId,jdbcType =BIGINT};
属性结果集映射:
BasePlusResultMap包含了属性查询语句的Collection
所以通过下面的查询商品语句就可获得商品以及其包含的属性集合:
select s.ID,s.SKU_NAME,s.CATEGORY_ID
from t_shop_sku s
where s.ID = #{id,jdbcType =BIGINT};