Envers fails to insert revision into @ElementCollection table when entity has a composite key containing a foreign key

Issue has been tested with Hibernate version 6.2.9.Final.

The following example fails with an exception: org.postgresql.util.PSQLException: ERROR: null value in column "foo_baz_id" of relation "foo_bars_aud" violates not-null constraint Detail: Failing row contains (1, 0, 0, null, abcdef, abcd). which is correct, as the column foo_baz_id is not allowed to be null as it is part of the composite key for the entity. What I don’t understand is why hibernate somehow tries to insert null for the foo_baz_id in the first place. Below is a minimal reproducible example:

Given the following Entity (omitted unrelated methods / constructors):

@Entity
@IdClass(FooId.class)
@Audited
public class Foo {
    @Id
    String id;
    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    Baz baz;

    @ElementCollection(fetch = FetchType.EAGER)
    private Set<Bar> bars = new HashSet<>();
}

The ManyToOne Entity for the foreign key is simple:

@Entity
public class Baz {
    @Id
    String id;

    String name;
}

The IdClass is the following:

public class FooId implements Serializable {
    public String id;
    public String baz;
}

And lastly the ElementCollection is a simple embeddable:

@Embeddable
public class Bar {
    @NotNull
    private String name;
    public Bar() {}
}

Trying to persist any change in the ElementCollection leads to the above mentioned error e.g.:

Baz baz = new Baz("test123", "name123");
bazRepository.save(baz);
Foo foo = new Foo(id, baz, new Bar("abcd"));
fooRepository.save(foo);

I’ve tested the same example with a composite key without a foreign relation and that seemed to work correctly. I assume this is a Hibernate Bug but am not 100% sure. Any idea where the issue lies or how I can circumvent it?

After some more trial and error, it maybe isn’t an error directly related to Hibernate envers, the issue seems to be in the way the lazy foreign key is included in the above code snippets. I changed the my Entity and my IdClass to directly contain the Id and using @JoinColumn for the foreign entity and the auditing works fine: e.g.

@Entity
@IdClass(FooId.class)
@Audited
public class Foo {
    @Id
    String id;
    @Id
    @Column(name= "baz_id")
    String bazId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
            @JoinColumn(name = "baz_id", insertable=false, updatable=false)
    })
    Baz baz;

    @ElementCollection
    private List<Bar> bars = new ArrayList<>();
}

and the IdClass:

public class FooId implements Serializable {
    public String id;
    public String bazId;
}

The above solution seems to resolve my initial issue.