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

时间:2015-07-01 11:42:38

标签: java hibernate hibernate-envers

我正面临Envers的问题。我有两个实体,CITY和CITY_I18N。 有一个"一对多"他们之间的关系,通过" CODE" CITY实体的列。 当我尝试保存CityI18N实体时,操作成功结束,但CITY_I18N_AUD表中的记录包含错误值,Envers写入" ID" CITY实体的列,而不是真正的外键," 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;
}

1 个答案:

答案 0 :(得分:0)

这是一个古老的问题,但是我最近也遇到了同样的问题,看来Envers yet仍未解决。

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

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

唯一的障碍是手动更改_AUD表中列的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)
);

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