简体   繁体   English

Hibernate 使用 ManyToOne 删除所有引用 object 单向的对象关联

[英]Hibernate delete all objects associations that reference the object unidirectional using ManyToOne

I have a ModuleData object and a Setting object that references this ModuleData object, but the ModuleData object does not have any reference to the Setting object. Does Hibernate automatically delete the objects that reference ModuleData and if not, how do I accomplish that Hibernate does this. I have a ModuleData object and a Setting object that references this ModuleData object, but the ModuleData object does not have any reference to the Setting object. Does Hibernate automatically delete the objects that reference ModuleData and if not, how do I accomplish that Hibernate does this .

ModuleData.java ModuleData.java

@Entity
@Table(name = "modules")
public class ModuleData {

    @Id
    @GeneratedValue
    @Column(name = "id", updatable = false, nullable = false)
    private long id;

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

    @Column(name = "version")
    private String version;
}

Setting.java设置.java

@Entity
@Table(name = "settings", uniqueConstraints = @UniqueConstraint(columnNames = {"settingKey"}))
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Setting {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

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

    @Column
    private String value;

    @ManyToOne
    @JoinColumn(name = "moduleId", nullable = false)
    private ModuleData module;

I will delete by session.delete(moduleData) .我将通过session.delete(moduleData)删除。

You can add the other side of the relation (ie add the Setting property to the ModuleData class), and then use Java Persistence 'cascade types' to accomplish this.您可以添加关系的另一端(即,将设置属性添加到 ModuleData 类),然后使用 Java Persistence“级联类型”来完成此操作。 Specifically the CascadeType.REMOVE will give you the desired behavior.具体来说,CascadeType.REMOVE 将为您提供所需的行为。 From this great tutorial , your ModuleData class would reference its Setting child similar to this:这个很棒的教程中,您的 ModuleData class 将引用它的 Setting 子项,类似于:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true)
private List<Comment> comments = new ArrayList<>();

so it would look something like:所以它看起来像:

@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, ...)
private List<Setting> settings;

Another great tutorial on cascade types:另一个关于级联类型的很棒的教程:

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

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