第7章 商品类别模块
2018-05-02 本文已影响0人
cuzz_
商品类别列表
Dao层的实现
- ProductCategoryDao接口
package com.imooc.o2o.dao;
import com.imooc.o2o.entity.ProductCategory;
import java.util.List;
public interface ProductCategoryDao {
/**
* 通过shop id 查询店铺的商品类别
* @param shopId
* @return
*/
List<ProductCategory> queryProductCategoryList(Long shopId);
}
- 在mapper中添加ProductCategoryDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.o2o.dao.ProductCategoryDao">
<select id="queryProductCategoryList" resultType="com.imooc.o2o.entity.ProductCategory" parameterType="Long">
SELECT
product_category_id,
product_category_name,
priority,
create_time,
shop_id
FROM
tb_product_category
WHERE
shop_id = #{shopId}
</select>
</mapper>
- 测试
package com.imooc.o2o.dao;
import com.imooc.o2o.BaseTest;
import com.imooc.o2o.entity.ProductCategory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class ProductCategoryDaoTest extends BaseTest {
@Autowired
private ProductCategoryDao productCategoryDao;
@Test
public void testQueryByShopId() throws Exception{
Long shopId = 4L;
List<ProductCategory> productCategorieList = productCategoryDao.queryProductCategoryList(shopId);
System.out.println("该店铺自定义类别数为:" + productCategorieList.size());
}
}
-
测试结果
image.png
Service层实现
- ProductCategoryService接口
package com.imooc.o2o.service;
import com.imooc.o2o.entity.ProductCategory;
import java.util.List;
public interface ProductCategoryService {
/**
* 查询指定某个店铺下的所有的商品类别信息
* @param shopId
* @return
*/
List<ProductCategory> getProductCategroyList(Long shopId);
}
- 实现类
package com.imooc.o2o.service.impl;
import com.imooc.o2o.dao.ProductCategoryDao;
import com.imooc.o2o.entity.ProductCategory;
import com.imooc.o2o.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class ProductCategoryServiceImpl implements ProductCategoryService {
@Autowired
private ProductCategoryDao productCategoryDao;
@Override
public List<ProductCategory> getProductCategroyList(Long shopId) {
List<ProductCategory> productCategoryList = productCategoryDao.queryProductCategoryList(shopId);
return productCategoryList;
}
}
Controller层的实现
- ProductCategoryManagementController类
@Controller
@RequestMapping("/shop")
public class ProductCategoryManagementController {
@Autowired
private ProductCategoryService productCategoryService;
@RequestMapping(value = "/getproductcategorylist", method = RequestMethod.GET)
@ResponseBody
private Map<String, Object> getProductCategoryList(HttpServletRequest request) {
Map<String, Object> modelMap = new HashMap<>();
// To be removed
Shop shop = new Shop();
shop.setShopId(4L);
request.getSession().setAttribute("currentShop", shop);
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
List<ProductCategory> list = null;
if (currentShop != null && currentShop.getShopId() > 0) {
list = productCategoryService.getProductCategroyList(currentShop.getShopId());
modelMap.put("list", list);
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errorMsg", "出错了");
}
return modelMap;
}
}
-
测试
image.png -
对Json封装
package com.imooc.o2o.dto;
/**
* 封装json对象,所有返回结果都使用它
*/
public class Result<T> {
private boolean success;// 是否成功标志
private T data;// 成功时返回的数据
private String errorMsg;// 错误信息
private int errorCode;
public Result() {
}
// 成功时的构造器
public Result(boolean success, T data) {
this.success = success;
this.data = data;
}
// 错误时的构造器
public Result(boolean success, int errorCode, String errorMsg) {
this.success = success;
this.errorMsg = errorMsg;
this.errorCode = errorCode;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
- 修改ProductCategoryManagementController
@Controller
@RequestMapping("/shop")
public class ProductCategoryManagementController {
@Autowired
private ProductCategoryService productCategoryService;
@RequestMapping(value = "/getproductcategorylist", method = RequestMethod.GET)
@ResponseBody
private Result<List<ProductCategory>> getProductCategoryList(HttpServletRequest request) {
// Map<String, Object> modelMap = new HashMap<>();
// To be removed
Shop shop = new Shop();
shop.setShopId(5L);
request.getSession().setAttribute("currentShop", shop);
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
List<ProductCategory> list = null;
if (currentShop != null && currentShop.getShopId() > 0) {
list = productCategoryService.getProductCategroyList(currentShop.getShopId());
// modelMap.put("list", list);
// modelMap.put("success", true);
return new Result<>(true, list);
} else {
// modelMap.put("success", false);
// modelMap.put("errorMsg", "出错了");
ProductCategoryStateEnum ps = ProductCategoryStateEnum.INNER_ERROR;
return new Result<>(false, ps.getState(), ps.getStateInfo());
}
// return modelMap;
}
}
-
测试
image.png -
返回页面
@RequestMapping(value = "/productcategorymanage")
public String ProductCategoryManage() {
return "shop/productcategorymanage";
}
-
测试
image.png
商品的批量添加
Dao层的实现
- 接口中添加方法
/**
* 批量新增商品类别
* @param productCategoryList
* @return
*/
int batchInsertProductCategory(List<ProductCategory> productCategoryList);
- mapper中
<insert id="batchInsertProductCategory" parameterType="java.util.List">
INSERT INTO
tb_product_category(product_category_name, priority, create_time, shop_id)
VALUES
<foreach collection="list" item="productCategory" index="index" separator=",">
(
#{productCategory.productCategoryName},
#{productCategory.priority},
#{productCategory.createTime},
#{productCategory.shopId}
)
</foreach>
</insert>
- 测试
@Test
public void testBatchInsertProductCategory() {
ProductCategory productCategory = new ProductCategory();
productCategory.setProductCategoryName("商铺类别1");
productCategory.setPriority(20);
productCategory.setCreateTime(new Date());
productCategory.setShopId(6L);
ProductCategory productCategory2 = new ProductCategory();
productCategory2.setProductCategoryName("商铺类别2");
productCategory2.setPriority(10);
productCategory2.setCreateTime(new Date());
productCategory2.setShopId(6L);
List<ProductCategory> productCategoryList = new ArrayList<>();
productCategoryList.add(productCategory);
productCategoryList.add(productCategory2);
int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
assertEquals(2, effectedNum);
}
-
测试结果
image.png
service层的实现
- ProductCategoryExecution
package com.imooc.o2o.dto;
import com.imooc.o2o.enmus.ProductCategoryStateEnum;
import com.imooc.o2o.entity.ProductCategory;
import java.util.List;
public class ProductCategoryExecution {
// 结果状态
private int state;
// 状态标识
private String stateInfo;
private List<ProductCategory> productCategoryList;
// 无参构造器
public ProductCategoryExecution() {
}
// 操作失败的有参构造器
public ProductCategoryExecution(ProductCategoryStateEnum stateEnum) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
}
// 操作成功使用的构造器
public ProductCategoryExecution(ProductCategoryStateEnum stateEnum, List<ProductCategory> productCategoryList) {
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
this.productCategoryList = productCategoryList;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
public List<ProductCategory> getProductCategoryList() {
return productCategoryList;
}
public void setProductCategoryList(List<ProductCategory> productCategoryList) {
this.productCategoryList = productCategoryList;
}
}
- ProductCategoryOperationException
package com.imooc.o2o.exceptiopns;
public class ProductCategoryOperationException extends RuntimeException {
public ProductCategoryOperationException(String msg) {
super(msg);
}
}
- 在接口中定义一个新的方法
/**
* 批量添加CategoryList
* @param productCategoryList
* @return
* @throws ProductCategoryOperationException
*/
ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
throws ProductCategoryOperationException;
- 实现类
@Override
// 事务管理
@Transactional
public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList)
throws ProductCategoryOperationException {
if (productCategoryList != null && productCategoryList.size() > 0) {
try {
int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
if (effectedNum <= 0) {
throw new ProductCategoryOperationException("店铺创建失败");
} else {
return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS, productCategoryList);
}
} catch (Exception e) {
throw new ProductCategoryOperationException("batchAddProductCategory error" + e.getMessage());
}
} else {
return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
}
}
}
controller层的实现
@RequestMapping(value = "/addproductcategorys", method = RequestMethod.POST)
@ResponseBody
// @RequestBody可以根据前端传入的list作为参数
private Map<String, Object> addProductCategory(HttpServletRequest request, @RequestBody List<ProductCategory> productCategoryList) {
Map<String, Object> modelMap = new HashMap<>();
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
// 给每个productCategory设置shopId
for (ProductCategory pc : productCategoryList) {
pc.setShopId(currentShop.getShopId());
}
if (productCategoryList != null && productCategoryList.size() > 0) {
try{
ProductCategoryExecution pce = productCategoryService.batchAddProductCategory(productCategoryList);
if (pce.getState() == ProductCategoryStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errMsg", pce.getStateInfo());
}
} catch (ProductCategoryOperationException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "请至少输入一个商品类别");
}
return modelMap;
}
- js
getList();
$('#submit').click(function () {
var tempArr = $('.temp');
var productCategoryList = [];
tempArr.map(function (index, item) {
var tempObj = {};
tempObj.productCategoryName = $(item).find('.category').val();
tempObj.priority = $(item).find('.priority').val();
if (tempObj.productCategoryName && tempObj.priority) {
productCategoryList.push(tempObj);
}
});
$.ajax({
url: addUrl,
type: 'POST',
data: JSON.stringify(productCategoryList),
contentType: 'application/json',
success: function (data) {
if (data.success) {
$.toast('提交成功!');
getList();
} else {
$.toast('提交失败!');
}
}
});
});
- 测试
image.png
image.png
发现没有按照priority排序,发现在mapper文件中sql语句中少了
ORDER BY
priority DESC
商品类别删除后端开发
Dao层的实现
- 接口
/**
* 删除指定的商品类别
* @param productCategoryId
* @param shopId
* @return
*/
int deleteProductCategory(@Param("productCategoryId") long productCategoryId, @Param("shopId") long shopId);
- mapper
我们有productCategoryId就可以确定,为什么还有shopId呢?
我们要做更安全的控制,就是shopId必须正确,就是预防删除到别的店铺的productCategoryID
<delete id="deleteProductCategory">
DELETE FROM
tb_product_category
WHERE
product_categroy_id = #{productCategoryId}
AND
shop_id = #{shopId}
</delete>
service层的实现
- 接口
/**
* 将此类别下的商品里的类别id置为空,在删除该商品类别
* @param productCategoryId
* @param shopID
* @return
* @throws ProductCategoryOperationException
*/
ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopID)
throws ProductCategoryOperationException;
- 实现类
因为删除了ProductCateogy所以里面的商品也要全部删除掉
@Override
@Transactional
public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopID) throws ProductCategoryOperationException {
// TODO 将此商品类别下的商品的类别Id置为空
try {
int effectedNum = productCategoryDao.deleteProductCategory(productCategoryId, shopID);
if (effectedNum <= 0) {
throw new ProductCategoryOperationException("店铺类别删除失败");
} else {
return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
}
} catch (Exception e) {
throw new ProductCategoryOperationException("deleteProductCategory error:" + e.getMessage());
}
}
Controller层的实现
- 删除
@RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST)
@ResponseBody
private Map<String, Object> removeProductCategory(HttpServletRequest request, Long productCategoryId) {
Map<String, Object> modelMap = new HashMap<>();
if (productCategoryId != null && productCategoryId > 0) {
try {
Shop currentShop = (Shop) request.getSession().getAttribute("currentShop");
ProductCategoryExecution pce = productCategoryService.deleteProductCategory(productCategoryId, currentShop.getShopId());
if (pce.getState() == ProductCategoryStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errMsg", pce.getStateInfo());
}
} catch (ProductCategoryOperationException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
} else {
modelMap.put("success", false);
modelMap.put("errMsg","请选择商品类别");
}
return modelMap;
}
-
报错
image.png
找了好久,原来是product_category_id 不是 product_categroy_id
-
测试
image.png
image.png