1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.jpetstore.service;
17
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21
22 import org.mybatis.jpetstore.domain.Item;
23 import org.mybatis.jpetstore.domain.Order;
24 import org.mybatis.jpetstore.domain.Sequence;
25 import org.mybatis.jpetstore.mapper.ItemMapper;
26 import org.mybatis.jpetstore.mapper.LineItemMapper;
27 import org.mybatis.jpetstore.mapper.OrderMapper;
28 import org.mybatis.jpetstore.mapper.SequenceMapper;
29 import org.springframework.stereotype.Service;
30 import org.springframework.transaction.annotation.Transactional;
31
32
33
34
35
36
37 @Service
38 public class OrderService {
39
40 private final ItemMapper itemMapper;
41 private final OrderMapper orderMapper;
42 private final SequenceMapper sequenceMapper;
43 private final LineItemMapper lineItemMapper;
44
45 public OrderService(ItemMapper itemMapper, OrderMapper orderMapper, SequenceMapper sequenceMapper,
46 LineItemMapper lineItemMapper) {
47 this.itemMapper = itemMapper;
48 this.orderMapper = orderMapper;
49 this.sequenceMapper = sequenceMapper;
50 this.lineItemMapper = lineItemMapper;
51 }
52
53
54
55
56
57
58
59 @Transactional
60 public void insertOrder(Order order) {
61 order.setOrderId(getNextId("ordernum"));
62 order.getLineItems().forEach(lineItem -> {
63 String itemId = lineItem.getItemId();
64 Integer increment = lineItem.getQuantity();
65 Map<String, Object> param = new HashMap<>(2);
66 param.put("itemId", itemId);
67 param.put("increment", increment);
68 itemMapper.updateInventoryQuantity(param);
69 });
70
71 orderMapper.insertOrder(order);
72 orderMapper.insertOrderStatus(order);
73 order.getLineItems().forEach(lineItem -> {
74 lineItem.setOrderId(order.getOrderId());
75 lineItemMapper.insertLineItem(lineItem);
76 });
77 }
78
79
80
81
82
83
84
85
86
87 @Transactional
88 public Order getOrder(int orderId) {
89 Order order = orderMapper.getOrder(orderId);
90 order.setLineItems(lineItemMapper.getLineItemsByOrderId(orderId));
91
92 order.getLineItems().forEach(lineItem -> {
93 Item item = itemMapper.getItem(lineItem.getItemId());
94 item.setQuantity(itemMapper.getInventoryQuantity(lineItem.getItemId()));
95 lineItem.setItem(item);
96 });
97
98 return order;
99 }
100
101
102
103
104
105
106
107
108
109 public List<Order> getOrdersByUsername(String username) {
110 return orderMapper.getOrdersByUsername(username);
111 }
112
113
114
115
116
117
118
119
120
121 public int getNextId(String name) {
122 Sequence sequence = sequenceMapper.getSequence(new Sequence(name, -1));
123 if (sequence == null) {
124 throw new RuntimeException(
125 "Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
126 }
127 Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
128 sequenceMapper.updateSequence(parameterObject);
129 return sequence.getNextId();
130 }
131
132 }