gpt4 book ai didi

java - Hibernate:从带有外键的关联表中删除记录

转载 作者:行者123 更新时间:2023-12-02 08:27:49 24 4
gpt4 key购买 nike

我是 hibernate 新手。所以,我不知道该怎么做:

我有 3 张 table :

餐 table 人员:

@Entity
@Table(name = "ASD_PERSON")
public class AsdPerson implements Serializable {
@Id
@SequenceGenerator(name="seq_name", sequenceName="gen_id_value", allocationSize = 1)
@GeneratedValue(generator="seq_name")
@Column(name="F_PERSON_ID", nullable = false)
private Long fPersonId;

@OneToMany(mappedBy = "AsdPerson",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<AsdPersonEvent> asdPersonEventList;

... setters and getters ...
}

表事件:

@Entity
@Table(name = "ASD_EVENT")
public class AsdEvent implements Serializable {
@Id
@SequenceGenerator(name="seq_name", sequenceName="gen_id_value", allocationSize = 1)
@GeneratedValue(generator="seq_name")
@Column(name="F_EVENT_ID", nullable = false)
private Long fEventId;

@OneToMany(mappedBy = "AsdEvent",
cascade = CascadeType.ALL,
orphanRemoval = true)
private List<AsdPersonEvent> asdPersonEventList;

... setters and getters ...
}

表人员-事件:

@Entity
@Table(name = "ASD_PERSON_EVENT")
@IdClass(AsdPersonEventPK.class)
public class AsdPersonEvent implements Serializable {
@Id
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "asdPerson"))
@GeneratedValue(generator = "generator")
@Column(name="F_PERSON_ID", nullable = false, insertable = false,
updatable = false)
private Long fPersonId;

@Id
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "asdEvent"))
@GeneratedValue(generator = "generator")
@Column(name="F_EVENT_ID", nullable = false, insertable = false,
updatable = false)
private Long fEventId;

@ManyToOne
@JoinColumn(name = "F_PERSON_ID", insertable = false,
updatable = false)
private AsdPerson asdPerson;

@ManyToOne
@JoinColumn(name = "F_EVENT_ID", insertable = false,
updatable = false)
private AsdEvent asdEvent;

... setters and getters ...
}

一切都很完美(添加新记录,创建新对象),除了当我尝试从事件表或人员表中删除关联记录时的情况:

...
AsdEvent ev = getService().get(115); // get record from Event table by id = 115 (for example)
ev.getAsdPersonEventList().remove(1); // delete some existing records
getService().merge(ev);
...

之后我收到错误:

deleted object would be re-saved by cascade (remove deleted object from associations): [database.AsdPersonEvent#database.AsdPersonEventPK@12908fc]

如何使用注释或其他方式配置 Hibernate 来消除此错误?

最佳答案

如果您有一个复杂的持久实体图,我认为您需要放弃使用orphanRemoval并使用em.remove()手动删除实体。

orphanRemoval 专为简单的父子关系而设计,在这种关系中,如果没有父项,子项就没有意义。如果您的 child 可能有其他关系,也许这不是orphanRemoval的好案例。

关于java - Hibernate:从带有外键的关联表中删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4153101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com