一对一关系在我的 Spring 引导后端中不起作用

One to one relationship doesn't work in my Spring Boot back-end

我正在 Spring 启动开发电子商务后端。 OrderPayment 这两个实体之间存在 1:1 关系。首先,我创建一个Paymentorder字段为空),当支付成功时(假设总是在这种情况下),我创建与创建的支付相关的订单。问题是创建了 Order 实体,但它没有与 Payment 实体连接,因为当我尝试在 PaymentService 中打印订单时,它说订单对于该付款仍然为空(即使在 createOrder 方法中,我做了 payment.setOrder(o);,如下所示)。此外,如果我尝试从数据库中删除付款,它会告诉我付款无法删除,因为它已连接到订单,但奇怪的是,当我尝试打印我创建的付款订单时,结果为空。

订单服务:

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) {
        System.out.println("UserId: "+userId);
        System.out.println("Payment: "+paymentId);
        System.out.println("cartId: "+cartId);
        if(userRepository.existsById(userId)){
            System.out.println("Exists");}
        User user = userRepository.findById(userId);
        if(user==null){
            System.out.println("User is null");
        }
        Payment payment = paymentRepository.findById(paymentId);
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        Order justAdded = orderRepository.save(o);
        entityManager.refresh(justAdded);
        entityManager.refresh(o);
        payment.setOrder(o);
        entityManager.refresh(payment);
        return justAdded;
    }
}

订单控制器:

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity<Order> createOrder (@RequestParam(required = false) int paymentId,
                                                    @RequestParam(required = false) int buyerId,
                                                    @RequestParam(required = false) int cartId){

            return new ResponseEntity<>(orderService.createOrder(paymentId, buyerId, cartId), HttpStatus.OK);

    }

支付服务:

@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Payment addPayment(Payment p) throws PaymentAlreadyExistsException, IncorrectCardNumberException, IncorrectCvvException{//
        if(paymentRepository.existsByCardNumber(p.getCardNumber())){
            throw new PaymentAlreadyExistsException();
        }
        if(p.getCardNumber().length()!=16){
            throw new IncorrectCardNumberException();
        }
        if(p.getCvv().length()!=3)
        {
            throw new IncorrectCvvException();
        }
        System.out.println("Sto salvando il pagamento: "+p);
        Order newOrder = new Order();
        newOrder.setPayment(p);
        Order justAdded=orderRepository.save(newOrder);
        entityManager.refresh(justAdded);
        p.setOrder(justAdded);


        return paymentRepository.save(p);
    }

支付控制器:

@RestController
@RequestMapping("/payments")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/createPayment")//funziona
    public ResponseEntity<Payment> create(@RequestBody @Valid Payment payment){
        System.out.print("Sono in paymentController.");
        try {
            Payment added=paymentService.addPayment(payment);
            return new ResponseEntity<>(added, HttpStatus.OK);
        } catch (PaymentAlreadyExistsException e) {
            return new ResponseEntity(new ResponseMessage("Payment already exists!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCardNumberException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect card number!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCvvException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect CVV"), HttpStatus.BAD_REQUEST);
        }
}
}

支付实体:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;


    @OneToOne(mappedBy = "payment")
    private Order order;


}

订单实体:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity

@Table(name = "order", schema = "purchase")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_time")
    private Date orderTime;

    @ManyToOne
    @JoinColumn(name = "buyer")
    private User buyer;



    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "payment_id")
    @JsonIgnore
    private Payment payment;

    @OneToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;
}

我在PaymentService中有以下方法:

@Transactional(readOnly = true)//
    public List<Payment> getAllPayments(){
        List<Payment> result = paymentRepository.findAll();
        for(Payment p: result){
            if(p.getOrder()==null)
            System.out.println("Order in payment is null");
        }
        return paymentRepository.findAll();
    }

当我执行它时(在创建 PaymentOrder 并尝试使用 createOrder 方法连接它们之后),

Order in payment is null

已打印,因此 Payment 的字段 order 仍然为空。

Order 对象是在数据库中以下列方式创建的:

我按照建议按以下方式编辑了 createOrder 方法,但问题仍然存在:

@Transactional(readOnly = false)
    public Order createOrder (int paymentId, int userId, int cartId) throws PaymentDoesNotExistException{
        User user = userRepository.findById(userId);
        Payment payment = paymentRepository.findById(paymentId);
        if(payment == null)
        { throw new PaymentDoesNotExistException();
        }
        System.out.println("Payment: "+payment);
        Cart c = cartRepository.findById(cartId);
        Order o = new Order();
        o.setPayment(payment);
        o.setCart(c);
        o.setBuyer(user);
        payment.setOrder(o);
        orderRepository.save(o);
        return o;

    }

我看到了一些不需要的东西。无需调用刷新。只需创建子对象并先保存它们,然后再保存父对象。这里只是一个指导,制作您自己的自定义异常和消息。

    Payment payment = paymentRepository.findById(paymentId);
    if(payment == null)
    { throw Exception("Payment not found");}
    System.out.println("Payment: "+payment);
    Cart c = cartRepository.findById(cartId);
    Order o = new Order();
    o.setPayment(payment);
    o.setCart(c);
    o.setBuyer(user);
    orderRepository.save(o);