Mybatis一对多关联查询

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的属性)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码不停蹄的玄黓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值