所以,我的代码运行得很好,但我现在意识到了一些不应该发生的事情. 每当我使用不存在的产品创建订单时,如下所示:

{
"cartItems": [
    {
        "productName": "teste52",
        "quantity": 7
    }
],
"userEmail": "nemsei@gmail22.com"
}

它只创建如下顺序:

{
"id": 1,
"user": {
    "userId": 1,
    "userName": null,
    "email": "nemsei@gmail22.com"
},
"cartItems": [
    {
        "id": 1,
        "productId": null,
        "productName": "teste52",
        "quantity": 7,
        "amount": 0.0
    }
],
"createdAt": "2023-01-06"
}

它应该给出一个错误,因为名为"teste52"的产品并不存在,相反,它正在创建该订单,即使没有该产品. 我的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;
    }
}

我的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);
    }
}

我的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 + '\'' +
                '}';
    }
}

我的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;

    }}

我可以做些什么,让它给出错误,而不是创建这样的订单?

推荐答案

您正在判断(并且需要判断)该产品是否存在的唯一地方就是这个街区

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;
    }

在这里,您将从数据库中获取productIdamount.

如果产品不存在,则不会执行if (product.isPresent()) 块,但不会执行函数getCartAmountstill returns normally,即cart.setProductIdcart.setAmount,因此提要中的值为空.

try 使用此If块执行Else

else {
// throw error
}

Java相关问答推荐

AlarmManager没有在正确的时间发送alert

使用java访问具体子类特定方法的最佳方法是什么?

Java中如何根据Font.canDisplay方法对字符串进行分段

名称冲突具有相同的擦除

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

测试何时使用Mockito强制转换对象会导致ClassCastException

为什么同步数据块无效?

如何在构建Gradle项目时排除com.google.guava依赖项的一个变体

Java SSLKeyManager出厂密码

二进制数据的未知编码/序列化

一对多关系和ID生成

AbstractList保证溢出到其他方法

除0错误/抱歉我的句子是PT

如何在MPAndroidChart中的条形图上正确添加标签

@此处不能应用可为null的批注

带有提取器的JavaFXObservableList会根据侦听器的存在而改变行为

Jackson YAML:支持锚点扩展/覆盖

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?

Hibernate try 在 CrudRepository 中插入 null id

使用 PDFBOX 打印 JPEG2000