【问题标题】:Update collection when remove the same entity from other collection从其他集合中删除相同实体时更新集合
【发布时间】:2013-04-18 18:21:05
【问题描述】:

我有 4 个类实体:CtPersonaFirma、CtFirmaDocumento 和 CtContrato。一个人可以签几份合同,一份合同可以多人签。

CtPersonaFirma:包含授权签署的人员。

CtContrato:包含合同

CtFirmaDocumento:上面两张表的关系。

当我删除一个人时,用于级联的 CtPersonaFirma 表删除了 CtFirmaDocumento 表,其中有对已删除人员的引用,但在实体 CtContrato 的集合 ctFirmaDocumentoCollection 中未更新。

public class CtContrato implements Serializable {
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id_contrato")
private Integer idContrato;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "ctContrato", fetch=FetchType.LAZY)
private Collection<CtFirmaDocumento> ctFirmaDocumentoCollection;


public class CtPersonaFirma implements Serializable {
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id_persona")
private Integer idPersona;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "ctPersonaFirma")
private Collection<CtFirmaDocumento> ctFirmaDocumentoCollection;

public class CtFirmaDocumento implements Serializable {
@EmbeddedId
protected CtFirmaDocumentoPK ctFirmaDocumentoPK;
@JoinColumn(name = "id_persona_ref", referencedColumnName = "id_persona", insertable = false, updatable = false)
@ManyToOne(optional = false)
private CtPersonaFirma ctPersonaFirma;
@JoinColumn(name = "id_contrato", referencedColumnName = "id_contrato", insertable = false, updatable = false)
@ManyToOne(optional = false)
private CtContrato ctContrato;

【问题讨论】:

    标签: jpa-2.0


    【解决方案1】:

    JPA 要求应用程序维护双向关系的双方。当您对一侧进行更改时,JPA 不会为您维护另一侧,并且您的缓存实体将与数据库中的内容不同步。根据您更改的哪一侧,这些更改也可能不会保留在数据库中。

    在这种情况下,当您删除 CtFirmaDocumento 对象时,您还应该删除任何可能引用它的 CtContrato 中对这些对象的所有引用。

    在这种情况下,另一种方法是在刷新或提交更改后强制刷新任何 CtContrato 对象,但通常最好直接修复引用以避免以后出现这种关系的问题。

    【讨论】:

    • 强制刷新,会出什么问题?
    • 是数据库命中访问,所以有性能成本。在具有未提交更改的实体上刷新将还原这些更改,这就是为什么我认为维护双方更容易,或者根本不映射 1:M。
    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 2016-11-08
    • 2021-09-23
    相关资源
    最近更新 更多