开发前的准备
我们在接到任务的时候比如需要开发一个商品模块,应该是不管三七二十一直接建立数据库呢还是思考数据模型呢。
1. 首先编写商品数据模型
public class ItemModel {
private Integer id;
//商品名称
@NotBlank(message = "商品名称不能为空")
private String title;
//商品价格
@NotNull(message = "商品价格不能为空")
@Min(value = 0,message = "商品价格必须大于0")
private BigDecimal price;
//商品的库存
@NotNull(message = "库存不能不填")
private Integer stock;
//商品的描述
@NotBlank(message = "商品描述信息不能为空")
private String description;
//商品的销量
private Integer sales;
//商品描述图片的url
@NotBlank(message = "商品图片信息不能为空")
private String imgUrl;
2. 建立数据库
这里我们需要小心,商品模型中包括了库存的信息,这里我们可以将库存的信息单独拆除一个数据表,这就是数据库的水平拆分(分库分表)。
DROP TABLE IF EXISTS `item`;
CREATE TABLE `item` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`price` DECIMAL(64, 2) NOT NULL DEFAULT 0.00,
`description` VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
`sales` INT(100) NOT NULL DEFAULT 0,
`img_url` VARCHAR(5000) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = INNODB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = COMPACT;
DROP TABLE IF EXISTS `item_stock`;
CREATE TABLE `item_stock` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`stock` INT(11) NOT NULL DEFAULT 0,
`item_id` INT(11) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = INNODB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = COMPACT;
3. 用mybatis生成 数据库映射
3. 对所有的Insert 操作添加useGeneratedKeys="true" keyProperty="id"
保证这两个表互相联系
4. service层编写
public interface ItemService {
//创建商品
ItemModel createItem(ItemModel itemModel) throws BusinessException;
//浏览商品
List<ItemModel> listItem();
//商品详情浏览
ItemModel getItemById(Integer id);
}
5. controller层编写
注意:controller层是为了减少代码,业务代码都放到service层中写
//创建商品的controller
@RequestMapping(value = "/create", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
@ResponseBody
public CommonReturnType createItem(@RequestParam(name = "title") String title,
@RequestParam(name = "description") String description,
@RequestParam(name = "price") BigDecimal price,
@RequestParam(name = "stock") Integer stock,
@RequestParam(name = "imgUrl") String imgUrl) throws BusinessException {
//封装service请求用来创建商品
ItemModel itemModel = new ItemModel();
itemModel.setTitle(title);
itemModel.setDescription(description);
itemModel.setPrice(price);
itemModel.setStock(stock);
itemModel.setImgUrl(imgUrl);
ItemModel itemModelForReturn = itemService.createItem(itemModel);
ItemVO itemVO = convertVOFromModel(itemModelForReturn);
return CommonReturnType.create(itemVO);
}
private ItemVO convertVOFromModel(ItemModel itemModel) {
if (itemModel == null) {
return null;
}
ItemVO itemVO = new ItemVO();
BeanUtils.copyProperties(itemModel, itemVO);
return itemVO;
}