springboot篇】二十一. 基於springboot電商項目 十二 訂單服務

中國加油,武漢加油!

篇幅較長,配合目錄觀看

案例準備

  1. 本案例基於springboot篇】二十一. 基於springboot電商項目 十一 地址服務

1. 訂單添加

1.1 修改shop-order的affirmOrder.html

在這裏插入圖片描述在這裏插入圖片描述

1.2 修改order表結構

在這裏插入圖片描述

1.3 shop-entity編寫Order類

package com.wpj.entity;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order implements Serializable{
    private String id; // id自己生成
    private Integer ostatus;
    private Integer uid;
    private BigDecimal totalPrice;
    private Date createTime;
    private String person;
    private String phone;
    private String address;
}

1.4 shop-common編寫工具類

package com.wpj.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OrderUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 訂單id的生成規則:時間(年月日)+用戶id後四位+流水號
    public String createOrderId(Integer userId) {
        StringBuffer orderId = new StringBuffer();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 給訂單號添加時間
        orderId.append(sdf.format(date));
        // 給訂單號添加用戶id後四位
        orderId.append(getUserIdEnd(userId));
        // 添加流水號(這裏不需要用stringRedisTemplate)
        Object order_num1 = stringRedisTemplate.opsForValue().get("order_num");
        if (order_num1 == null || "".equals(order_num1)) {
            stringRedisTemplate.opsForValue().set("order_num", "1");
        }
        Long order_num = stringRedisTemplate.opsForValue().increment("order_num");
        orderId.append(order_num.toString());
        return orderId.toString();
    }
    public String getUserIdEnd(Integer userId) {
        String tempUid = userId.toString();
        StringBuffer uId = new StringBuffer();
        if (tempUid.length() < 4) {
            uId.append(tempUid);
            for (int i = 0; i < 4 - (tempUid.length()); i++) {
                uId.insert(0, "0");
            }
        } else {
            uId.append(tempUid.substring(tempUid.length() - 4));
        }
        return uId.toString();
    }
}

1.5 shop-mapper定義Mapper接口

package com.wpj.mapper;

import com.wpj.entity.Order;

public interface IOrderMapper {
    public int addOrder(Order order);
}

1.6 shop-service-api定義Service接口

package com.wpj.service;

import com.wpj.entity.Order;

public interface IOrderService {
    public int addOrder(Order order);
}

1.5 shop-service-iml新建order-service(module-springboot)

1.5.1 order-service定義ServiceImpl

package com.wpj.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.wpj.entity.Order;
import com.wpj.mapper.IOrderMapper;
import com.wpj.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderMapper orderMapper;

    @Override
    public int addOrder(Order order) {
        return orderMapper.addOrder(order);
    }
}

1.5.2 配置yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/nz1904-springboot-shop
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
  redis:
    host: 192.168.59.100
    password: admin
mybatis-plus:
  type-aliases-package: com.wpj.entity
  mapper-locations: classpath:/mapper/*.xml
dubbo:
  application:
    name: order-service
  registry:
    address: zookeeper://192.168.59.100:2181
  protocol:
    port: -1

1.6 shop-service-api的ICartService編寫方法

BigDecimal getTotalPrice(List<Cart> cartList);
void deleteCartByUid(Integer id);

1.7 cart-service重寫方法

@Override
public BigDecimal getTotalPrice(List<Cart> cartList) {
    BigDecimal totalPrice = new BigDecimal(0);
    for(Cart cart:cartList){
        totalPrice= totalPrice.add(cart.getSubTotal());
    }
    return totalPrice;
}

@Override
public void deleteCartByUid(Integer id) {
    EntityWrapper entityWrapper = new EntityWrapper();
    entityWrapper.eq("uid",id);
    cartMapper.delete(entityWrapper);
}

1.8 shop-mapper定義IOrderMapper.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.wpj.mapper.IOrderMapper">
    <insert id="addOrder">
		INSERT INTO t_order (
			id,
			total_price,
			ocreate_time,
			ostatus,
			u_id,
			person,
			phone,
			address
		)
		VALUES
			(
			  #{id},
			  #{totalPrice},
			  #{createTime},
			  #{ostatus},
			  #{uid},
			  #{person},
			  #{phone},
			  #{address}
			)
	</insert>
</mapper>

1.9 修改order-service的程序入口

package com.wpj;

import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.wpj")
@DubboComponentScan(basePackages = "com.wpj.service")
@MapperScan(basePackages = "com.wpj.mapper")
public class OrderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }

}

1.10 Test

package com.wpj;

import com.alibaba.dubbo.config.annotation.Reference;
import com.wpj.common.utils.OrderUtils;
import com.wpj.entity.Order;
import com.wpj.service.IOrderService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
class OrderServiceApplicationTests {
    @Reference
    private IOrderService orderService;

    @Autowired
    private OrderUtils orderUtils;

    @Test
    void contextLoads() {
        Order order = new Order();
        String orderId = orderUtils.createOrderId(14);
        order.setId(orderId);
        orderService.addOrder(order);
    }

}

在這裏插入圖片描述

1.11 shop-entity定義OrderDetail類

package com.wpj.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.math.BigDecimal;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderDetail implements Serializable{

    private Integer id;
    private String oid;
    private Integer gid;
    private String gname;
    private Integer  gnum;
    private String gpic;
    private BigDecimal gprice;
    private BigDecimal gcount;
    private String gdesc;
}

1.12 修改t_order_detail

在這裏插入圖片描述

1.13 shop-mapper定義Mapper接口

package com.wpj.mapper;

import com.wpj.entity.OrderDetail;

import java.util.List;

public interface IOrderDetailMapper {
    public int addBarch(List<OrderDetail> list);
}

1.14 shop-service-api定義Service接口

package com.wpj.service;

import com.wpj.entity.OrderDetail;

import java.util.List;

public interface IOrderDetailService {
    public int addBarch(List<OrderDetail> list);
}

1.15 order-service定義ServiceImpl實現類

package com.wpj.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.wpj.entity.OrderDetail;
import com.wpj.mapper.IOrderDetailMapper;
import com.wpj.service.IOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class OrderDetailServiceImpl implements IOrderDetailService {

    @Autowired
    private IOrderDetailMapper orderDetailMapper;

    @Override
    public int addBarch(List<OrderDetail> list) {
        return orderDetailMapper.addBarch(list);
    }
}

1.16 shop-mapper定義IOrderDetailMapper.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.wpj.mapper.IOrderDetailMapper">
	
	<insert id="addBarch">
		INSERT INTO t_order_detail (
				id,
				oid,
				gid,
				gname,
				gprice,
				gnum,
				gcount,
				gpic,
				gdesc
			)
			VALUES
			<foreach collection="list" item="od" separator=",">
				(
					#{od.id},
					#{od.oid},
					#{od.gid},
					#{od.gname},
					#{od.gprice},
					#{od.gnum},
					#{od.gcount},
					#{od.gpic},
					#{od.gdesc}
				)
			</foreach>
	</insert>
</mapper>

1.17 Test

@Reference
private IOrderDetailService orderDetailService;

@Test
public void test2(){
    List<OrderDetail> orderDetailList = new ArrayList<>();
    orderDetailList.add(new OrderDetail());
    orderDetailService.addBarch(orderDetailList);
}

在這裏插入圖片描述

1.18 shop-order的OrderController編寫方法

@Reference
private IOrderService orderService;
@Reference
private IOrderDetailService orderDetailService;

@RequestMapping("/addOrder")
@IsLogin(mustUser = true)
@ResponseBody
public String addOrder(Integer addressId,User user){
    // 根據地址id查詢地址的對象
    Address address = addressService.selectById(addressId);
    List<Cart> cartList = cartService.getUserCartList(user,"");
    // 插入訂單
    Order order = new Order();
    String orderId = orderUtils.createOrderId(user.getId());
    order.setId(orderId);
    order.setUid(user.getId());
    order.setPerson(address.getPhone());
    order.setAddress(address.getAddress());
    order.setCreateTime(new Date());
    order.setOstatus(0); // 0 未支付 1 已支付 2 超時 3 取消
    order.setPerson(address.getPerson());
    order.setTotalPrice(cartService.getTotalPrice(cartList));
    orderService.addOrder(order);
    // 插入訂單詳情
    List<OrderDetail> orderDetailList = new ArrayList<>();
    for (Cart cart: cartList) {
        OrderDetail orderDetail = new OrderDetail();
        Goods goods = cart.getGoods();
        orderDetail.setGprice(goods.getGprice());
        orderDetail.setGpic(goods.getGpic());
        orderDetail.setGnum(cart.getNum());
        orderDetail.setGname(goods.getGname());
        orderDetail.setGid(goods.getId());
        orderDetail.setGcount(cart.getSubTotal());
        orderDetail.setGdesc(goods.getGdesc());
        orderDetailList.add(orderDetail);
        
        if (orderDetailList.size() == 300) {
            orderDetailService.addBarch(orderDetailList);
            orderDetailList.clear();
        }
        
    }
    if (orderDetailList.isEmpty()){
        orderDetailService.addBarch(orderDetailList);
    }
    // 清空購物車
    cartService.deleteCartByUid(user.getId());
    // 跳轉到支付頁面
    return "ok";
}

1.19 啓動程序入口測試

有個亂碼問題待解決

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章