-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrderService.java
More file actions
266 lines (215 loc) · 7.43 KB
/
OrderService.java
File metadata and controls
266 lines (215 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// 1. Entity Classes
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String email;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Order> orders = new ArrayList<>();
// Getters, setters, constructors
}
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@Column(name = "order_date")
private LocalDateTime orderDate;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> items = new ArrayList<>();
@Enumerated(EnumType.STRING)
private OrderStatus status;
// Getters, setters, constructors
}
@Entity
@Table(name = "order_items")
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
private Integer quantity;
@Column(name = "unit_price")
private BigDecimal unitPrice;
// Getters, setters, constructors
}
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String description;
@Column(nullable = false)
private BigDecimal price;
@Version
private Integer version;
// Getters, setters, constructors
}
// 2. Repository Interfaces
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
@Query("SELECT u FROM User u LEFT JOIN FETCH u.orders WHERE u.id = :userId")
Optional<User> findByIdWithOrders(@Param("userId") Long userId);
@Query(value = "SELECT * FROM users WHERE LOWER(username) LIKE LOWER(CONCAT('%', :search, '%'))",
nativeQuery = true)
List<User> searchByUsername(@Param("search") String search);
}
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUserIdAndStatusOrderByOrderDateDesc(Long userId, OrderStatus status);
@Query("SELECT o FROM Order o " +
"JOIN FETCH o.user " +
"JOIN FETCH o.items i " +
"JOIN FETCH i.product " +
"WHERE o.id = :orderId")
Optional<Order> findByIdWithDetails(@Param("orderId") Long orderId);
}
// 3. Service Layer
@Service
@Transactional
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public User createUser(UserDTO userDTO) {
// Check if username already exists
if (userRepository.findByUsername(userDTO.getUsername()).isPresent()) {
throw new UserAlreadyExistsException("Username already taken");
}
User user = new User();
user.setUsername(userDTO.getUsername());
user.setEmail(userDTO.getEmail());
// Additional setup...
return userRepository.save(user);
}
@Transactional(readOnly = true)
public User getUserWithOrders(Long userId) {
return userRepository.findByIdWithOrders(userId)
.orElseThrow(() -> new UserNotFoundException("User not found"));
}
}
@Service
@Transactional
public class OrderService {
private final OrderRepository orderRepository;
private final UserRepository userRepository;
private final ProductRepository productRepository;
public OrderService(OrderRepository orderRepository,
UserRepository userRepository,
ProductRepository productRepository) {
this.orderRepository = orderRepository;
this.userRepository = userRepository;
this.productRepository = productRepository;
}
public Order createOrder(OrderDTO orderDTO) {
User user = userRepository.findById(orderDTO.getUserId())
.orElseThrow(() -> new UserNotFoundException("User not found"));
Order order = new Order();
order.setUser(user);
order.setOrderDate(LocalDateTime.now());
order.setStatus(OrderStatus.PENDING);
// Process order items
for (OrderItemDTO itemDTO : orderDTO.getItems()) {
Product product = productRepository.findById(itemDTO.getProductId())
.orElseThrow(() -> new ProductNotFoundException("Product not found"));
OrderItem item = new OrderItem();
item.setOrder(order);
item.setProduct(product);
item.setQuantity(itemDTO.getQuantity());
item.setUnitPrice(product.getPrice());
order.getItems().add(item);
}
return orderRepository.save(order);
}
@Transactional(readOnly = true)
public Order getOrderWithDetails(Long orderId) {
return orderRepository.findByIdWithDetails(orderId)
.orElseThrow(() -> new OrderNotFoundException("Order not found"));
}
}
// 4. DTOs
@Data
public class UserDTO {
private String username;
private String email;
// Other fields...
}
@Data
public class OrderDTO {
private Long userId;
private List<OrderItemDTO> items;
}
@Data
public class OrderItemDTO {
private Long productId;
private Integer quantity;
}
// 5. Custom Exceptions
public class UserAlreadyExistsException extends RuntimeException {
public UserAlreadyExistsException(String message) {
super(message);
}
}
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
// 6. Configuration
@Configuration
public class JpaConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource,
JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.domain");
em.setJpaVendorAdapter(jpaVendorAdapter);
Properties props = new Properties();
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.format_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "update");
em.setJpaProperties(props);
return em;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.POSTGRESQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
return adapter;
}
}
// 7. application.properties
/*
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
*/