Spring Data Jpa - ManyToMany - 删除连接表的实体 [英] Spring Data Jpa - ManyToMany - delete entities of the join table

查看:21
本文介绍了Spring Data Jpa - ManyToMany - 删除连接表的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这两个类:

public class ClassA extends [...] implements [...] {
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = JOIN_TABLE_NAME,
            joinColumns = @JoinColumn(name = COLUMN_REF_A, referencedColumnName = COLUMN_ID_A),
            inverseJoinColumns = @JoinColumn(name = COLUMN_REF_B, referencedColumnName = COLUMN_ID_B))
    private List<ClassB> fieldClassB;   
}

public class ClassB extends [...] implements [...] {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "fieldClassB", cascade = CascadeType.ALL)
    private List<ClassA> fieldClassA;

}

当我删除 ClassB(通过 spring 数据 jpa 存储库)时,Hibernate 也会删除 ClassA 的实例,而我只想要 JOIN_TABLE_NAME表要删除(另一个问题是,由于级联模式,删除ClassA实体的同时删除了这些ClassA<引用的其他ClassB/code>).

When I delete ClassB (via the spring data jpa repository), Hibernate also deletes instances of ClassA, whereas I just want the rows in the JOIN_TABLE_NAME table to be deleted (the other issue is that, due to the cascade mode, deleting the ClassA entities also delete other ClassB referenced by these ClassA).

有没有办法在不必创建连接实体并通过引用新连接实体的 @OneToMany 替换 @ManyToMany 注释的情况下处理这个问题?

Is there any way to handle this without having to create the join entity and to replace the @ManyToMany annotations by @OneToMany referencing the new join entity ?

推荐答案

在 manyToMany 中级联删除它不仅适用于链接表,还适用于关联的另一侧.

Cascade Remove in a manyToMany it's not only applied to the link table, but to the other side of the association as well.

因此,继承 remove 的 Cascade.ALL 在多对多上几乎总是一件坏事,因为它最终不仅会从关联表中删除内容.

So Cascade.ALL which inherit remove too is almost always a bad thing to have on a manyToMany as it ends up deleting things not only from association table.

您想要的是在实体中添加和删除方法来完成工作并保持两个列表同步:

What you want is to have add and remove method in your entities to do the work and keep both list synchronized:

public class ClassA extends [...] implements [...] {
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinTable(name = JOIN_TABLE_NAME,
            joinColumns = @JoinColumn(name = COLUMN_REF_A, referencedColumnName = COLUMN_ID_A),
            inverseJoinColumns = @JoinColumn(name = COLUMN_REF_B, referencedColumnName = COLUMN_ID_B))
    private List<ClassB> fieldClassB; 

    public void addClassB(ClassB b) {
        fieldClassB.add(b);
        b.fieldClassA().add(this);
    }

    public void removeClassB(ClassB b) {
        fieldClassB.remove(b);
        b.fieldClassA().remove(this);
    }  
}

这篇关于Spring Data Jpa - ManyToMany - 删除连接表的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆