1.问题描述
一个商品关联多个商品属性,查询某条商品信息时需要把与之关联的商品属性查询出来。
2.解决办法
数据表中,将商品主键放到与之管理的商品属性表做外键,在商品实体中添加一个商品属性列表字段保存商品属性。
2.1商品实体
@ApiModelProperty(value = "商品属性")
@TableField(exist = false)
private List<Attribute> attributes;
2.2商品Mapper.xml
resultMap:
<resultMap id="ProductMap" extends="BaseResultMap" type="com.edu.server.pojo.Product">
<collection property="attributes" column="id"
select="com.edu.server.mapper.AttributeMapper.getAttributeList" />
</resultMap>
注意:collection中不要加resultType
select:
<select id="getProductById" resultMap="ProductMap">
select * from t_product where id = #{productId}
</select>
2.3商品属性
mapper:
public List<Attribute> getAttributeList(Integer commodityId);
mapper.xml
<select id="getAttributeList" resultMap="BaseResultMap">
select * from t_attribute where cid = #{ commodityId }
</select>
2.4查询结果
关键点:
- 商品实体中添加attributes字段
- 商品id放到属性表做外键
- collection中column中的值为商品id(即将商品id传给属性mapper去查询外键为商品id的属性)