简体   繁体   English

Hibernate OneToMany ManyToOne 删除级联

[英]Hibernate OneToMany ManyToOne on delete cascade

I'm trying to use Hibernate to map the following relationship:我正在尝试使用 Hibernate 到 map 以下关系:

Each order contains 2 images.每个订单包含 2 张图片。 When I delete an order I want the images gone as well.当我删除订单时,我希望图像也消失。

I have two entities, OrderItems and Image and they look like this我有两个实体,OrderItems 和 Image,它们看起来像这样

public class OrderItems {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ID")
    private Long id;

    @Transient
    private String language;

    @OneToMany(fetch = FetchType.EAGER ,orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "order")
    private List<Image> images ;
}

public class Image implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ID")
    private Long id;

    @Column(name = "IMAGE_NAME")
    private String name;

    @Column(name = "IMAGE_BYTES", unique = false, nullable = true, length = 1000000)
    private byte[] image;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "order_id" , nullable = false)
    private OrderItems order;
}

Inserting new orders will also insert the coresponding images but when I try to delete an order I get an foreign key constraint error from the tables Image插入新订单也会插入相应的图像,但是当我尝试删除订单时,我从表图像中得到外键约束错误

Am I missing something about Hibernate?我是否遗漏了有关 Hibernate 的信息? Shouldn't the attribute cascade = CascadeType.ALL do the trick?属性 cascade = CascadeType.ALL 不应该这样做吗?

Thanks for taking the time to provide any feedback.感谢您花时间提供任何反馈。 Cheers干杯

I already tried OneToMany and ManyToOne unidirectional and bidirectional but I get the same foreign key violation error or my images are not saved at all when I save a new order.我已经尝试过 OneToMany 和 ManyToOne 单向和双向,但我遇到了相同的外键违规错误,或者当我保存新订单时我的图像根本没有保存。

I solved the issue by using Spring to delete an order and automagically it also deleted the images corresponding to that order.我通过使用 Spring 删除订单解决了这个问题,它也自动删除了与该订单对应的图像。

So my first approach of deleting orders by executing sql queries directly on the DB was the issue.因此,我通过直接在数据库上执行 sql 查询来删除订单的第一种方法就是问题所在。

Try like this像这样尝试

@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)

@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "order_id", nullable = false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM