Hibernate @OneToMany Mapping - 删除记录的问题

Hibernate @OneToMany Mapping - issues with deleting records

在我的应用程序中,我想将应用程序中的所有图像放在一个 table 中。上次发了个有人推荐我用unidirectional @OneToMany.

我有以下与 Image 实体相关联的实体

@Entity
@Table(name="promotion")
public class Promotion {

    @Id
    @Column(name="id")
    protected String id;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="itemId")
    protected List<Image> images = new ArrayList<>(); 
}


@Entity
@Table(name="product")
public class Product {

    @Id
    @Column(name="id")
    protected String id;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="itemId")
    protected List<Image> images = new ArrayList<>(); 
}


@Entity
@Table(name="image")
public class Image{

    @Id
    @Column(name="id")
    private String id = IdGenerator.createId();

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

    @Column(name="title", nullable = false)
    protected String title;

    @Column(name="filename", nullable = false)
    protected String filename;

    @Column(name="path", unique = true)
    private String path;

    @Column(nullable = true)
    protected int width;

    @Column(nullable = true)
    protected int height;
}

现在面临的问题是:

A) 当我在 images ArrayList 属性上使用 cascade={CascadeType.PERSIST, CascadeType.MERGE} 时,出现此异常:

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

所以我用 cascade=CascadeType.ALL 替换了它,当我保存 ProductPromotion 时,关联的 Image(s) 也被保存了,这很酷,这就是我想要的

B) 我现在遇到的主要问题是,当我删除 ProductPromotion 时,其相关图像永远不会被删除。他们的关联图像保留在 image table.

通过使用 cascade=CascadeType.ALL 我希望当我删除 ProductPromotion 时,它的图像也应该自动删除。我试图从数据库中删除一个图像,如果它会触发其关联的 ProductPromotion 被删除,但它没有,因为我认为它是单向的,这是有道理的。但是,当我删除 ProductPromotion 时,为什么它的关联图像不会被删除

在两个关系中添加orphanRemoval = true

@OneToMany(cascade = CascadeType.ALL,
            fetch = FetchType.EAGER,
            orphanRemoval = true)

这将

apply the remove operation to entities that have been removed from the relationship and to cascade the remove operation to those entities.