Disabling issuing of additional query when the joined entity is not found

Hello,
I have a following use-case: I have to traverse through the whole database table and perform some operations on the entities. The problem is, some of the data for these entities is stored on another table - this data can exist, but it is not required. I use composite key to join the data. There is no foreign key constraint between these two tables. My code for the entity looks like this:

@Entity
@Table(name = "DATA")
public class DataJPA {
 
   //key and other fields

   @OneToOne
   @NotFound(action = NotFoundAction.IGNORE)
   @JoinColumnOrFormula(column = @JoinColumn(name = "ID", referencedColumnName = "ID", table = "DATA", insertable = false, updatable = false, foreignKey = @javax.persistence.ForeignKey(ConstraintMode.NO_CONSTRAINT)))
   @JoinColumnOrFormula(column = @JoinColumn(name = "VALUE_ONE", referencedColumnName = "VALUE_ONE", table = "DATA", insertable = false, updatable = false, foreignKey = @javax.persistence.ForeignKey(ConstraintMode.NO_CONSTRAINT)))
   @JoinColumnOrFormula(column = @JoinColumn(name = "VALUE_TWO", referencedColumnName = "VALUE_TWO", table = "DATA", insertable = false, updatable = false, foreignKey = @javax.persistence.ForeignKey(ConstraintMode.NO_CONSTRAINT)))
   @JoinColumnOrFormula(formula = @JoinFormula(value = "'value'", referencedColumnName = "VALUE_THREE"))
   private AdditionalDataJPA additionalData;

}

The above code works fine - Hibernate produces LEFT OUTER JOIN for the AdditionalDataJPA and gets the data eagerly (I use setFetchMode(“additionalData”, FetchMode.JOIN)). But, the problem occurs when the data which Hibernate tries to join does not exist - Hibernate produces an additional query, which is not needed in this case, because I want it to return null for additionalData when the data can not be joined.
I saw many topics about this case and in most of them the responses were that the problem lies in the wrong model of the database - there should not be any data that can not be found and joined, but I think that the following responses only apply to cases where there is a foreign key constraint between tables. Is there any option to disable the Hibernate issuing additional query-check when the data is not found on join?

This might get resolved as part of this PR as we just noticed this behavior ourselves, but we can’t guarantee that this will happen in 5.x: https://github.com/hibernate/hibernate-orm/pull/4793

1 Like