当前位置:网站首页>Transaction module development
Transaction module development
2022-07-16 07:28:00 【Get an offer as soon as possible】
Create a transaction domain model OrderModel
package com.miaoshaproject.service.model;
import java.math.BigDecimal;
// A transaction model where users place orders
public class OrderModel {
// Transaction No 2022050500128
private String id;
// Users who buy id
private Integer userId;
// Purchased goods id
private Integer itemId;
// If not empty , It means that the order is placed in the form of second kill goods
private Integer promoId;
// Unit price of purchased goods , if promoId Non empty , It means that the commodity price is spike
private BigDecimal itemPrice;
// Purchase quantity
private Integer amount;
// Purchase amount
private BigDecimal orderPrice;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public BigDecimal getItemPrice() {
return itemPrice;
}
public void setItemPrice(BigDecimal itemPrice) {
this.itemPrice = itemPrice;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public BigDecimal getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(BigDecimal orderPrice) {
this.orderPrice = orderPrice;
}
public Integer getPromoId() {
return promoId;
}
public void setPromoId(Integer promoId) {
this.promoId = promoId;
}
}
The unit price and total amount of goods in the corresponding database table are double data type .OrderModel and OrderDO Attention should be paid to the mutual transformation
OrderService And its implementation
When creating an order, you need to consider whether there is activity for the product , And the activity from which you click to enter this product . So we need an activity id Parameters promoId. It is worth mentioning , This parameter does not have to .controller When receiving parameters , This parameter required=false
Transaction process :
- Verify the order status
- Make an order and reduce inventory / Pay less inventory ( The latter will lead to oversold )
- Order warehousing
- Back to front
In addition, you can only place an order after logging in , So you need to get login information , Use session obtain , If there is no corresponding parameter , Then go to the login page , Log them in , After logging in, jump to the product list page .
When creating an order , You need to create an order number , Use here 16 Bit order number , front 8 Bit time is , after 6 Bit is an auto increasing sequence , The last two are sub database and sub epitope . Autoincrement sequence uses sequence_info Table implementation . In addition, when obtaining the self increasing sequence , Corresponding sql It needs to be locked for update. In addition, the auto increment sequence will auto increment whether the order is successful or not , That is, after the order transaction fails to be created ,sequence Do not rollback to remain globally unique , So in correspondence with getSequenceByName Annotate the method @Transactional(propagation=Propagation.REQUIRES_NEW), Open a new transaction , Whether the order transaction is rolled back , The new transaction will be committed .
package com.miaoshaproject.service;
import com.miaoshaproject.error.BusinessException;
import com.miaoshaproject.service.model.OrderModel;
public interface OrderService {
// 1、 Through the front end url Uploaded seckill activity id, Then check the correspondence in the order interface id Whether it belongs to the corresponding product and the activity has started
// 2、 Directly judge whether there is a second kill activity for the corresponding commodity in the order interface , If there are in progress, place an order at the second kill price
// The first scheme is recommended : What you get is the seckill on the user access path id, In addition, for flat goods , There is no need for second judgment
OrderModel createOrder(Integer userId, Integer itemId,Integer promoId, Integer amount) throws BusinessException;
}
package com.miaoshaproject.service.impl;
import com.miaoshaproject.dao.OrderDOMapper;
import com.miaoshaproject.dao.SequenceDOMapper;
import com.miaoshaproject.dataobject.OrderDO;
import com.miaoshaproject.dataobject.SequenceDO;
import com.miaoshaproject.error.BusinessException;
import com.miaoshaproject.error.EmBussinessError;
import com.miaoshaproject.service.ItemService;
import com.miaoshaproject.service.OrderService;
import com.miaoshaproject.service.UserService;
import com.miaoshaproject.service.model.ItemModel;
import com.miaoshaproject.service.model.OrderModel;
import com.miaoshaproject.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private ItemService itemService;
@Autowired
private UserService userService;
@Autowired
private OrderDOMapper orderDOMapper;
@Autowired
private SequenceDOMapper sequenceDOMapper;
@Override
@Transactional
public OrderModel createOrder(Integer userId, Integer itemId, Integer promoId, Integer amount) throws BusinessException {
// 1、 Verify the order status , Whether the goods ordered exist , Whether the user is legal , Is the purchase quantity correct
ItemModel itemById = itemService.getItemById(itemId);
if(itemById == null) {
throw new BusinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, " Product information does not exist ");
}
UserModel userById = userService.getUserById(userId);
if(userById == null) {
throw new BusinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, " User information does not exist ");
}
if(amount <= 0 || amount > 99) {
throw new BusinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, " The purchase quantity is illegal ");
}
// Verify activity information
if(promoId != null) {
//(1) Verify whether this applicable product exists in this activity
if(promoId != itemById.getPromoModel().getId()) {
throw new BusinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR," The activity information is incorrect ");
} else if(itemById.getPromoModel().getStatus() != 2) {
//(2) Check whether the activity is in progress
throw new BusinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR," The event hasn't started yet ");
}
}
// 2、 Make an order and reduce inventory
boolean result = itemService.decreaseStock(itemId, amount);
if(!result) {
throw new BusinessException(EmBussinessError.STOCK_NOT_ENOUGH);
}
// 3、 Order warehousing
OrderModel orderModel = new OrderModel();
orderModel.setUserId(userId);
orderModel.setItemId(itemId);
orderModel.setAmount(amount);
if(promoId != null) {
orderModel.setItemPrice(itemById.getPromoModel().getPromoItemPrice());
} else {
orderModel.setItemPrice(itemById.getPrice());
}
orderModel.setPromoId(promoId);
orderModel.setOrderPrice(orderModel.getItemPrice().multiply(new BigDecimal(amount)));
// Generate transaction serial number ( The order number )
orderModel.setId(generateOrderNo());
OrderDO orderDO = convertFromOrderModel(orderModel);
orderDOMapper.insertSelective(orderDO);
// Plus the sales of goods
itemService.increaseSales(itemId, amount);
// 4、 Back to front
return orderModel;
}
private OrderDO convertFromOrderModel(OrderModel orderModel) {
if(orderModel == null) {
return null;
}
OrderDO orderDO = new OrderDO();
BeanUtils.copyProperties(orderModel, orderDO);
// take BigDecimal(Model) Turn into double( database )
orderDO.setItemPrice(orderModel.getItemPrice().doubleValue());
orderDO.setOrderPrice(orderModel.getOrderPrice().doubleValue());
return orderDO;
}
// Open a new transaction , In any case, the new transaction will be committed , Ensure that the autoincrement sequence is not rolled back , Make sure the whole situation is unique
@Transactional(propagation = Propagation.REQUIRES_NEW)
public String generateOrderNo() {
// Order No 16 position
StringBuffer stringBuffer = new StringBuffer();
// front 8 Bit time information , Specific date
LocalDateTime now = LocalDateTime.now();
String nowDate = now.format(DateTimeFormatter.ISO_DATE).replace("-","");
stringBuffer.append(nowDate);
// middle 6 Bit auto increment sequence , adopt sequence_info Table implementation
// Get current sequence
int sequence = 0;
SequenceDO sequenceDO = sequenceDOMapper.getSequenceByName("order_info");
sequence = sequenceDO.getCurrentValue();
sequenceDO.setCurrentValue(sequenceDO.getCurrentValue() + sequenceDO.getStep());
sequenceDOMapper.updateByPrimaryKeySelective(sequenceDO);
String sequenceStr = String.valueOf(sequence);
for(int i = 0; i + sequenceStr.length() < 6; i++) {
stringBuffer.append("0");
}
stringBuffer.append(sequenceStr);
// The last two bits are sub database and sub table (0-99) userId Yes 100 Remainder , Write for the time being
stringBuffer.append("00");
return stringBuffer.toString();
}
}
Corresponding front page . Refresh the page when the order is placed successfully :window.location.reload();
边栏推荐
猜你喜欢

七、SAN和NAS环境下的安全实施方案实验报告

Flink On Yarn HA模式搭建问题

SAP ABAP smartforms stepped on the pit

Volatile最终解释

SAP BW extraction layer error s:aa 821 (bukrs)

2021-11-7bugku做题记录25——POST

六、数据备份软件的配置实验报告

Mise en œuvre du rapport d'expérience RAID logiciel
![Du test de fonction au test automatique pour doubler le salaire, mon guide d'apprentissage Super complet [joindre les notes d'apprentissage]](/img/59/dfc87939871832548acecc8ef1d2bf.jpg)
Du test de fonction au test automatique pour doubler le salaire, mon guide d'apprentissage Super complet [joindre les notes d'apprentissage]

攻防世界web
随机推荐
Minimum cycle section in KMP
redis基础知识——菜鸟教程
【LeetCode】728. 自除数
[learning records on June 5]
When byte hung up, the interviewer asked me DDD, but I didn't know
MySql锁机制
"The following signature cannot be verified because there is no public key" solution
组合模式应用
Implementation of dynamic array vector class template
Implementation of binarysearchtree (BST) class template for binary search tree
Get started with promise
Hash table
六、数据备份软件的配置实验报告
【Oracle】在docker中配置Oracle数据库
368. Maximum divisible subset dynamic programming
【LeetCode】1252. 奇数值单元格的数目
JVM principle and Practice
三、FreeNas实现SMB共享、FTP搭建实验报告
SAP DUMP CX_SY_CONVERSION_NO_NUMBER
【LeetCode】1217. 玩筹码