有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多个关联中级联删除状态的java问题

我对包含零件的删除订单有问题。我尝试了CascadeType和fetch,但作为响应,我得到了错误:

Referential integrity constraint violation: "FKM25VEWW7LF2YTLPXGFELPMCEI: PUBLIC.ORDER_PARTS FOREIGN KEY(PART_ID) REFERENCES PUBLIC.PART(ID_PART) (3)"; SQL statement:
delete from part where id_part=?
@Entity
@Table(name = "client_order")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_order")
    private Long id;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name = "order_parts",
            joinColumns = {@JoinColumn(name="client_order_id", referencedColumnName="id_order")},
            inverseJoinColumns = {@JoinColumn(name="part_id", referencedColumnName="id_part")})
    private List<Part> parts = new ArrayList<>();

    @ManyToOne
    @JoinColumn(name = "id_client")
    private Client client;

    public Order() {
    }

    public Order(Long id) {
        this.id = id;
    }
}

@Entity
public class Part {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_part")
    private Long id;

    @Column(name = "part_name", nullable = false)
    private String name;

    @Column(name = "price")
    private Double price;

    @Column(name = "selected", nullable = false, columnDefinition = "boolean default false" )
    private boolean selected;

    @Enumerated(EnumType.STRING)
    private Category category;

    @ManyToMany(mappedBy = "parts")
    private List<Order> orders = new ArrayList<>();

    public Part() {
    }

    public Part(String name, Double price, boolean selected) {
        this.name = name;
        this.price = price;
        this.selected = selected;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    控制器

    @PostMapping("/deleteOrder/{id}")
    public String deleteOrder(@PathVariable Long id) {
        orderService.deleteOrder(id);
        return "redirect:/";
    }
    

    服务

    @Transactional
    public Order findOrderById(Long id) {
        Optional<Order> order = orderRepository.findById(id);
        if (order.isPresent()) {
            return order.get();
        } else {
            throw new RuntimeException();
        }
    }
    
    @Transactional
    public void deleteOrder(Long id) {
        Order order = findOrderById(id);
        orderRepository.delete(order);
    }
    
  2. # 2 楼答案

    正如hibernate documentation中所述:

    For @ManyToMany associations, the REMOVE entity state transition doesn’t make sense to be cascaded because it will propagate beyond the link table. Since the other side might be referenced by other entities on the parent-side, the automatic removal might end up in a ConstraintViolationException.