Search code examples
javahibernatehibernate-envers

Hibernate - Envers Writes Wrong Data to AUD Column


I am facing a problem with Envers. I have two entities, CITY and CITY_I18N. There is an "One-to-Many" relationship between them, via "CODE" column of CITY entity. When I try to save CityI18N entity, the operation ends successfully, but the record in CITY_I18N_AUD table contains wrong values, Envers writes "ID" column of CITY entity, instead of real foreign key, "CODE" column.

How can I fix this?

Thanks in advance.

@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;
}

Solution

  • This is an old question, but I had the same exact issue recently and it seems it is still not addressed in Envers yet.

    My solution was to just let Envers write the data from the @Id column into the referencedColumnName column of the _AUD table.

    It seems to be able to reconstruct the relationships fine.

    The only obstacle is to manually change the SQL data type of the column in the _AUD table:

    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)
    );
    

    This might not work for all use cases, but it at least keeps relationship intact.