分析
数据库设计
代码开发
判断当前商品是否已经在购物车中 如果在购物车中,更新购物车中商品数量 如果不在购物车中,添加到购物车
controller层
@PostMapping ( "/add" )
@ApiOperation ( "添加购物车" )
public Result add ( @RequestBody ShoppingCartDTO shoppingCartDTO) {
log. info ( "添加购物车:{}" , shoppingCartDTO) ;
shoppingCartService. addShoppingCart ( shoppingCartDTO) ;
return Result . success ( ) ;
}
service层
@Override
public void addShoppingCart ( ShoppingCartDTO shoppingCartDTO) {
ShoppingCart shoppingCart = new ShoppingCart ( ) ;
BeanUtil . copyProperties ( shoppingCartDTO, shoppingCart) ;
shoppingCart. setUserId ( BaseContext . getCurrentId ( ) ) ;
List < ShoppingCart > list = shoppingCartMapper. list ( shoppingCart) ;
if ( CollUtil . isNotEmpty ( list) ) {
ShoppingCart cart = list. get ( 0 ) ;
cart. setNumber ( cart. getNumber ( ) + 1 ) ;
shoppingCartMapper. updateNumberById ( cart) ;
} else {
Long dishId = shoppingCart. getDishId ( ) ;
if ( BeanUtil . isNotEmpty ( dishId) ) {
Dish dish = dishMapper. getById ( dishId) ;
shoppingCart. setName ( dish. getName ( ) ) ;
shoppingCart. setImage ( dish. getImage ( ) ) ;
shoppingCart. setAmount ( dish. getPrice ( ) ) ;
} else {
Long setmealId = shoppingCart. getSetmealId ( ) ;
Setmeal setmeal = setmealMapper. getById ( setmealId) ;
shoppingCart. setName ( setmeal. getName ( ) ) ;
shoppingCart. setImage ( setmeal. getImage ( ) ) ;
shoppingCart. setAmount ( setmeal. getPrice ( ) ) ;
}
shoppingCart. setNumber ( 1 ) ;
shoppingCart. setCreateTime ( LocalDateTime . now ( ) ) ;
shoppingCartMapper. insert ( shoppingCart) ;
}
}
mapper层
@Mapper
public interface ShoppingCartMapper {
List < ShoppingCart > list ( ShoppingCart shoppingCart) ;
@Update ( "update shopping_cart set number = #{number} where id = #{id}" )
void updateNumberById ( ShoppingCart cart) ;
@Insert ( "insert into shopping_cart(name, user_id, dish_id, setmeal_id, dish_flavor, number, amount, image, create_time) " +
"values" +
"(#{name}, #{userId}, #{dishId}, #{setmealId}, #{dishFlavor}, #{number}, #{amount}, #{image}, #{createTime})" )
void insert ( ShoppingCart shoppingCart) ;
}