创建订单
1 创建数据表
CREATE TABLE t_order
(
oid INT AUTO_INCREMENT COMMENT '订单id',
uid INT NOT NULL COMMENT '用户id',
recv_name VARCHAR(20) NOT NULL COMMENT '收货人姓名',
recv_phone VARCHAR(20) COMMENT '收货人电话',
recv_province VARCHAR(15) COMMENT '收货人所在省',
recv_city VARCHAR(15) COMMENT '收货人所在市',
recv_area VARCHAR(15) COMMENT '收货人所在区',
recv_address VARCHAR(50) COMMENT '收货详细地址',
total_price BIGINT COMMENT '总价',
status INT COMMENT '状态:0-未支付,1-已支付,2-已取消,3-已关闭,4-已完成',
order_time DATETIME COMMENT '下单时间',
pay_time DATETIME COMMENT '支付时间',
created_user VARCHAR(20) COMMENT '创建人',
created_time DATETIME COMMENT '创建时间',
modified_user VARCHAR(20) COMMENT '修改人',
modified_time DATETIME COMMENT '修改时间',
PRIMARY KEY (oid)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
CREATE TABLE t_order_item
(
id INT AUTO_INCREMENT COMMENT '订单中的商品记录的id',
oid INT NOT NULL COMMENT '所归属的订单的id',
pid INT NOT NULL COMMENT '商品的id',
title VARCHAR(100) NOT NULL COMMENT '商品标题',
image VARCHAR(500) COMMENT '商品图片',
price BIGINT COMMENT '商品价格',
num INT COMMENT '购买数量',
created_user VARCHAR(20) COMMENT '创建人',
created_time DATETIME COMMENT '创建时间',
modified_user VARCHAR(20) COMMENT '修改人',
modified_time DATETIME COMMENT '修改时间',
PRIMARY KEY (id)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
order.sql
2 创建实体类
1.订单实体类
Order
package com.cy.store.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
/** 订单数据的实体类 */
public class Order extends BaseEntity implements Serializable {
private Integer oid;
private Integer uid;
private String recvName;
private String recvPhone;
private String recvProvince;
private String recvCity;
private String recvArea;
private String recvAddress;
private Long totalPrice;
private Integer status;
private Date orderTime;
private Date payTime;
//---
}
2.订单项实体类
OrderItem
package com.cy.store.entity;
import java.io.Serializable;
import java.util.Objects;
/** 订单中的商品数据 */
public class OrderItem extends BaseEntity implements Serializable {
private Integer id;
private Integer oid;
private Integer pid;
private String title;
private String image;
private Long price;
private Integer num;
//---
}
Object
3 持久层
3.1 规划SQL语句
1.将数据插入到订单表中。
insert into t_order (oid除外的所有字段) values(字段的值)
2.将数据插入到订单项的表中。
insert into t_order_item (id除外的所有字段) values(字段的值)
3.2 设计接口与抽象方法
创建一个OrderMapper接口,接口中添加以上两个SQL语句的抽象方法。
package com.cy.store.mapper;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
/**订单的持久层接口*/
public interface OrderMapper {
/**
* 插入订单数据
* @param order 订单数据
* @return 受影响的行数
*/
Integer insertOrder(Order order);
/**
* 插入订单项的数据
* @param orderItem 订单项的数据
* @return 受影响的行数
*/
Integer insertOrderItem(OrderItem orderItem);
}
3.3 配置SQL映射
创建OrderMapper.xml的映射文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "http:///dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.store.mapper.OrderMapper">
<insert id="insertOrder" useGeneratedKeys="true" keyProperty="oid">
INSERT INTO t_order (
uid, recv_name, recv_phone, recv_province, recv_city, recv_area, recv_address,
total_price, status, order_time, pay_time, created_user, created_time, modified_user,
modified_time
)VALUES (
#{uid}, #{recvName}, #{recvPhone}, #{recvProvince}, #{recvCity}, #{recvArea},
#{recvAddress}, #{totalPrice}, #{status}, #{orderTime}, #{payTime}, #{createdUser},
#{createdTime}, #{modifiedUser}, #{modifiedTime}
)
</insert>
<insert id="insertOrderItem" useGeneratedKeys="true" keyProperty="id">
INSERT INTO t_order_item (
oid, pid, title, image, price, num, created_user,
created_time, modified_user, modified_time
) VALUES (
#{oid}, #{pid}, #{title}, #{image}, #{price}, #{num}, #{createdUser},
#{createdTime}, #{modifiedUser}, #{modifiedTime}
)
</insert>
</mapper>
OrderMapper–insertOrder
测试
OrderMapperTests
package com.cy.store.mapper;
import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.List;
//@SpringBootTest:表示标注当前的类是测试类,不会随同项目一块打包
@SpringBootTest
//@RunWith:表示启动这个单元测试类(单元测试类是不能够运行的),需要传递一个参数,必须是SpringRunner的实例类型
//@RunWith(SpringRunner.class)
public class OrderMapperTests {
@Autowired
private OrderMapper orderMapper;
@Test
void insertOrder(){
Order order=new Order();
order.setUid(8);
order.setRecvName("明明");
order.setRecvPhone("17857704444");
orderMapper.insertOrder(order);
}
@Test
void insertOrderItem(){
OrderItem orderItem = new OrderItem();
orderItem.setOid(1);
orderItem.setPid(10000003);
orderItem.setTitle("广博(GuangBo)16K115页线圈记事本子日记本文具笔记本图案随机");
orderMapper.insertOrderItem(orderItem);
}
}
OrderMapperTests–insertOrder
4 业务层
4.1 实现接口与抽象方法
1.在AddressService接口中定义根据收货地址的id获取收货地址数据。
Address getByAid(Integer aid,Integer uid);
2.在子类中实现改抽象方法。
@Override
public Address getByAid(Integer aid,Integer uid) {
Address address = addressMapper.findByAid(aid);
if (address==null){
throw new AddressNotFoundException("收货地址数据不存在");
}
if (!address.getUid().equals(uid)){
throw new AccessDeniedException("非法数据访问的异常");
}
address.setProvinceCode(null);
address.setCityCode(null);
address.setAreaCode(null);
address.setCreatedUser(null);
address.setCreatedTime(null);
address.setModifiedUser(null);
address.setModifiedTime(null);
return address;
}
AddressService–getByAid
3.在service包下创建IOrderService接口添加抽象方法用于创建订单。
package com.cy.store.service;
import com.cy.store.entity.Order;
public interface IOrderService {
Order create(Integer aid, Integer uid, String username, Integer[] cids);
}
4.2 实现抽象方法
4.创建实现类OrderServiceImpl类。
package com.cy.store.service.impl;
import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.ICartService;
import com.cy.store.service.IOrderService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class OrderServiceImpl implements IOrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private IAddressService addressService;
@Autowired
private ICartService cartService;
@Override
public Order create(Integer aid, Integer uid, String username, Integer[] cids) {
//即将下单的列表
List<CartVO> list = cartService.getVOByCid(uid, cids);
//计算商品的总价
Long totalPrice=0L;
for (CartVO c: list) {
totalPrice+=c.getRealPrice()*c.getNum();
}
Address address = addressService.getByAid(aid, uid);
//插入数据
Order order=new Order();
order.setUid(uid);
//收货地址数据
order.setRecvName(address.getName());
order.setRecvPhone(address.getPhone());
order.setRecvProvince(address.getProvinceName());
order.setRecvCity(address.getCityName());
order.setRecvArea(address.getAreaName());
order.setRecvAddress(address.getAddress());
//支付、总价、时间
order.setStatus(0);
order.setTotalPrice(totalPrice);
order.setOrderTime(new Date());
//日志
order.setCreatedUser(username);
order.setCreatedTime(new Date());
order.setModifiedUser(username);
order.setModifiedTime(new Date());
Integer rows = orderMapper.insertOrder(order);
if (rows!=1){
throw new InsertException("插入数据异常");
}
//创建订单详细项的数据
for (CartVO c: list) {
//创建一个订单项数据对象
OrderItem orderItem=new OrderItem();
orderItem.setOid(order.getOid());
orderItem.setPid(c.getPid());
orderItem.setTitle(c.getTitle());
orderItem.setImage(c.getImage());
orderItem.setPrice(c.getRealPrice());
orderItem.setNum(c.getNum());
//日志
orderItem.setCreatedUser(username);
orderItem.setCreatedTime(new Date());
orderItem.setModifiedUser(username);
orderItem.setModifiedTime(new Date());
//插入数据操作
rows=orderMapper.insertOrderItem(orderItem);
if (rows!=1){
throw new InsertException("插入数据异常");
}
}
return order;
}
}
OrderService–create
测试
package com.cy.store.service;
import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
//@SpringBootTest:表示标注当前的类是测试类,不会随同项目一块打包
@SpringBootTest
//@RunWith:表示启动这个单元测试类(单元测试类是不能够运行的),需要传递一个参数,必须是SpringRunner的实例类型
//@RunWith(SpringRunner.class)
public class OrderServiceTests {
@Autowired
private IOrderService orderService;
@Test
public void create(){
Integer[] cids={4,5};
Order order = orderService.create(6, 8, "红红", cids);
System.out.println(order);
}
}
OrderServiceTests–create
5 控制层
5.1 处理异常
无
5.2 设计请求
1.设计请求
/orders.create
aid,session,cids
post
JsonResult<Order>
5.3 处理请求
2.创建OrderController类,并编写请求处理方法。
package com.cy.store.controller;
import com.cy.store.entity.Order;
import com.cy.store.service.IOrderService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RequestMapping("/orders")
@RestController
public class OrderController extends BaseController{
@Autowired
private IOrderService orderService;
@RequestMapping("create")
public JsonResult<Order> create(Integer aid, Integer[] cids, HttpSession session) {
Integer uid=getuidFromSession(session);
String username = getUsernameFromSession(session);
Order data = orderService.create(aid, uid, username, cids);
return new JsonResult<>(OK,data);
}
}
OrderController–create
测试
略
6 前端页面
在订单确定页面中添加发送请求的处理方法。
// create
$("#btn-create-order").click(function() {
let aid = $("#address-list").val();//5
let cids = location.search.substr(1);//cids=4&cids=5
$.ajax({
url: "/orders/create",
type: "GET",
data: "aid="+aid + "&" +cids,//aid=5&cids=4&cids=5
dataType: "JSON",
success: function(json) {
if (json.state == 200) {
location.href = "payment.html";
alert("订单创建成功");
console.log(json.data)
}
},
error: function(xhr) {
alert("订单数据加载产生未知的异常" + xhr.status);
}
});
});
// create
orderConfirm.html–create
测试
README–创建订单