Querying a nullable @OneToOne relationship with JPA

Yes it can be done without performing join and using JPA query. Check out the following code snippet:

@Entity
class Entity1 {
   ...
   @OneToOne(...)
   @JoinColumn(name="entity2ID")
   private Entity2 entity2;
   @Column(name="entity2ID", nullable=true, insertable=true, updatable=true)
   private Long entity2ID;
   ...
}

Simply map the joining column in entity as insertable/updatable as FALSE. The Make sure that you absolutely not provide setter method for xyz or joining column. Once this is done you can use following query:

SELECT e FROM Entity1 e WHERE e.entity2ID IS NULL

This won't perform any joins as you are querying for joining column directly.


You can simply run this JPQL query:

SELECT e1 
FROM Entity1 e1 
LEFT JOIN e1.entity2 e2
WHERE e2 IS NULL

The LEFT JOIN is what you were looking for.