Hibernate - Envers 将错误数据写入 AUD 列

Hibernate - Envers Writes Wrong Data to AUD Column

我遇到了 Envers 的问题。我有两个实体,CITY 和 CITY_I18N。 通过 CITY 实体的 "CODE" 列,它们之间存在 "One-to-Many" 关系。 当我尝试保存 CityI18N 实体时,操作成功结束,但 CITY_I18N_AUD table 中的记录包含错误值,Envers 写入 CITY 实体的 "ID" 列,而不是真正的外键, "CODE" 列。

我该如何解决这个问题?

提前致谢。

@Entity
@Audited
public class City  {

    @Id
    @SequenceGenerator(name = "CITY_ID_GENERATOR", sequenceName = "SEQ_CITY")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CITY_ID_GENERATOR")
    private Long ID;

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

    @OneToMany(mappedBy = "city", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    @Fetch(value = FetchMode.SUBSELECT)
    @NotAudited
    private List<CityI18n> cityI18ns;
}

@Entity
@Table(name="CITY_I18N")
@Audited
public class CityI18n {

    @Id
    @SequenceGenerator(name="CITY_I18N_ID_GENERATOR", sequenceName="SEQ_APPLICATION")
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CITY_I18N_ID_GENERATOR")
    private Long ID;

    private String name;

    @ManyToOne
    @JoinColumn(name = "LANGUAGE_CODE", referencedColumnName="CODE")
    private Language language;

    @ManyToOne
    @JoinColumn(name = "CITY_CODE", referencedColumnName="CODE")
    private City city;
}

这是一个老问题,但我最近遇到了完全相同的问题,似乎在 Envers yet 中仍未解决。

我的解决方案是让 Envers 将 @Id 列中的数据写入 _AUD table 的 referencedColumnName 列。

似乎可以很好地重建关系。

唯一的障碍是手动更改 _AUD table 中列的 SQL 数据类型:

CREATE TABLE CITY_AUD (
    ID int8 NOT NULL,
    REV int8 NOT NULL,
    REVTYPE int2,
    REVEND int8,   -- if you are using ValidityAuditStrategy
    CODE varchar(255),
    PRIMARY KEY (ID, REV)
);

CREATE TABLE CITY_I18N_AUD (
    ID int8 NOT NULL,
    REV int8 NOT NULL,
    REVTYPE int2,
    REVEND int8,   -- if you are using ValidityAuditStrategy
    NAME varchar(255),
    CITY_CODE int8, -- Notice the type is int8 here - it will actually hold the CITY.ID not CITY.CITY_CODE
    LANGUAGE_CODE int8, -- assuming it's the same situation for LANGUAGE (wasn't clear from the question)
    PRIMARY KEY (ID, REV)
);

这可能不适用于所有用例,但至少可以保持关系完整。