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?