1、数据库
品牌表
CREATE TABLE `tb_brand` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '品牌id',
`name` varchar(50) NOT NULL COMMENT '品牌名称',
`image` varchar(200) DEFAULT '' COMMENT '品牌图片地址',
`letter` char(1) DEFAULT '' COMMENT '品牌的首字母',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=325402 DEFAULT CHARSET=utf8 COMMENT='品牌表,一个品牌下有多个商品(spu),一对多关系';
商品分类表
CREATE TABLE `tb_category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '类目id',
`name` varchar(20) NOT NULL COMMENT '类目名称',
`parent_id` bigint(20) NOT NULL COMMENT '父类目id,顶级类目填0',
`is_parent` tinyint(1) NOT NULL COMMENT '是否为父节点,0为否,1为是',
`sort` int(4) NOT NULL COMMENT '排序指数,越小越靠前',
PRIMARY KEY (`id`),
KEY `key_parent_id` (`parent_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1424 DEFAULT CHARSET=utf8 COMMENT='商品类目表,类目和商品(spu)是一对多关系,类目与品牌是多对多关系';
关联表
CREATE TABLE `tb_category_brand` (
`category_id` bigint(20) NOT NULL COMMENT '商品类目id',
`brand_id` bigint(20) NOT NULL COMMENT '品牌id',
PRIMARY KEY (`category_id`,`brand_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品分类和品牌的中间表,两者是多对多关系';
2、controller
还是一样,先分析四个内容:
- 请求方式:刚才看到了是
POST
- 请求路径:
/brand
- 请求参数:brand 对象,外加商品分类的 id 数组 cids
- 返回值:无
代码:在 BrandController
里面书写
/**
* 新增品牌
* @param brand
* @param cids
* @return
*/
@PostMapping
public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids){
brandService.saveBrand(brand, cids);
return ResponseEntity.status(HttpStatus.CREATED).build(); // 有返回,请求 body;没有返回,请求 build。
}
3、Service
这里要注意,我们不仅要新增品牌,还要维护品牌和商品分类的中间表。
@Transactional
public void saveBrand(Brand brand, List<Long> cids) {
// 新增品牌
brand.setId(null);
int count = brandMapper.insert(brand);
if(count != 1){
throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);
}
//新增中间表
for (Long cid : cids) {
count = brandMapper.insertCategoryBrand(cid, brand.getId());
if(count != 1){
throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);
}
}
}
这里调用了brandMapper
中的一个自定义方法,来实现中间表的数据新增
4、Mapper
通用 Mapper 只能处理单表,也就是 Brand 的数据,因此我们手动编写一个方法及 sql,实现中间表的新增:
package com.leyou.item.mapper;
import com.leyou.item.pojo.Brand;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;
public interface BrandMapper extends Mapper<Brand> {
/**
* 新增商品分类和品牌中间表数据
* @param cid
* @param bid
* @return
*/
@Insert("INSERT INTO tb_category_brand (category_id, brand_id) VALUES (#{cid}, #{bid})")
int insertCategoryBrand(@Param("cid") Long cid, @Param("bid") Long bid);
}