This involves one-to-one and many-to-one associations that are non-optional, where the associated entity ID is non-null, but there is no entity with that ID. This can only happen when there is no foreign key constraint on the association ID.
There are 3 some cases where Hibernate will load an entity with a null association, even though the the association is non-optional:
1) The mapping includes {{@NotFound(action = NotFoundAction.IGNORE)}}. For example:
{code:java} @Entity public void Employment { @Id private long id;
@ManyToOne(optional=false) @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) private Employee employee; {code}
{{@NotFound(action = NotFoundAction.IGNORE)}} is not compatible with a non-optional association. Hibernate should throw a {{MappingException}} when this is detected.
2) The mapping has {{@OneToOne(optional = false) @MapsId}} {{@Fetch(value = FetchMode.SELECT)}, with {{@JoinColumn}} used to override the column name. For example:
{code:java} @Entity public void Employment { @Id private long id;
@OneToOne(optional=false) @MapsId @JoinColumn(name = "FK", @JoinColumn(foreignKey=@ForeignKey(NO_CONSTRAINT))) @Fetch(value = FetchMode.SELECT) private Employee employee; } {code}
3) The mapping has {{@OneToOne(optional = false)}} with {{@PrimaryKeyJoinColumn}}, and {{@Fetch(value = FetchMode.SELECT)}}. For example:
{code:java} @Entity public void Employment { @Id private long id;
@OneToOne(optional = false) @PrimaryKeyJoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) @Fetch(value = FetchMode.SELECT) @NotFound(action = NotFoundAction.EXCEPTION) private Employee employee; } {code}
NOTE: Currently, the foreign key constraint cannot be disabled via @JoinColumn(foreignKey=@ForeignKey(NO_CONSTRAINT)) for 2) or 3) due to HHH-12975. When testing, the foreign key will need to be dropped, or the {{Employment}} table will have to be dropped and recreated without the foreign key.
For cases 2) and 3), Hibernate should return null for loaded {{Employment}}, since it is impossible to have a non-null {{Employment.employee}}. |
|