So, my code runs just fine, but I'm now aware of something that is not supposed to happen. Whenever I create an order, with an unexisting product,like this :
{
"cartItems": [
{
"productName": "teste52",
"quantity": 7
}
],
"userEmail": "[email protected]"
}
it just creates the order like this:
{
"id": 1,
"user": {
"userId": 1,
"userName": null,
"email": "[email protected]"
},
"cartItems": [
{
"id": 1,
"productId": null,
"productName": "teste52",
"quantity": 7,
"amount": 0.0
}
],
"createdAt": "2023-01-06"
}
It is supposed to give an error, because the product with the name "teste52" doesn't exist but instead, it's creating that order, even without that product. My order.java
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
@ToString
@Entity
@Table(name = "myorder")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "userId")
private User user;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
@JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
@CreationTimestamp
@Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public Order(int Id, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
this.createdAt = createdAt;
this.id = Id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My orderService.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
public List<Order> getAllOrderDetail(LocalDate yesterday, LocalDate today) {
today = LocalDate.now();
yesterday = today.minusDays(1);
return orderRepository.findAllByCreatedAtBetween(yesterday, today);
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderDTO.java
package com.proj.my.dto;
import com.proj.my.model.ShoppingCart;
import java.util.List;
public class OrderDTO {
private List<ShoppingCart> cartItems;
private String userEmail;
private String userName;
public OrderDTO() {
}
public OrderDTO(List<ShoppingCart> cartItems, String userEmail, String userName) {
this.cartItems = cartItems;
this.userEmail = userEmail;
this.userName = userName;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
public String getuserEmail() {
return userEmail;
}
public void setuserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "OrderDTO{"
", cartItems=" cartItems
", userEmail='" userEmail '\''
", userName='" userName '\''
'}';
}
}
My orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
@RestController
@RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
@Autowired
private CloudProductRepository cloudProductRepository;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
@GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(@PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
@GetMapping(value = "/getOrders/{dataaa}")
public List<Order> getAllOrderDetails(@PathVariable LocalDate dataaa) {
return orderService.getAllOrderDetail(dataaa);
}
@PostMapping("/placeOrder")
public ResponseEntity<String> placeOrder(@RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
List<ShoppingCart> shoppingCartList = orderDTO.getCartItems();
ShoppingCart shoppingCart;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()){
float amount = orderService.getCartAmount(orderDTO.getCartItems());
User user = new User(orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return new ResponseEntity<>("Created", HttpStatus.OK);
}
else{
return new ResponseEntity<>("Can't", HttpStatus.OK);
}
}
return null;
}}
What can I do so that it gives an error instead of creating such order ?
CodePudding user response:
The only place where you are checking (and need to check) whether the product exists or not is in this block
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
Here you are fetching the productId
and amount
from the database.
If product doesn't exist, then if (product.isPresent())
block is not executed but the function getCartAmount
still returns normally i.e. cart.setProductId
and cart.setAmount
are not executed and hence are null in your feed.
Try an else with this if block
else {
// throw error
}