EntityNotFoundException for lazy OneToOne association using a derived key in Hibernate

Solution Verified - Updated -

Issue

  • An entity is defined with an optional unidirectional OneToOne lazy association making the primary key a derived key

    @Entity
    public class Employee {
        @Id
        private String id;
    
        @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = true)
        @JoinColumn(name = "id", referencedColumnName = "id") // make the primary key derived/foreign
        @NotFound(action = NotFoundAction.IGNORE)
        @LazyToOne(LazyToOneOption.NO_PROXY)
        private Plan plan;
        ...
    }
    
    @Entity
    public class Plan {
        @Id
        private String id;
        ...
    }
    
  • Since the primary key must be initialized but the association using the derived primary key is optional, the foreign key constraint is omitted for the association so that the primary key behaves as a pseudo-foreign key (i.e. it has no referential integrity).

  • When the associated row corresponding to the derived primary key value does not exist, calling the association accessor method results in an exception:

    ... Unable to find support.hibernate.entity.Plan with id 1234: javax.persistence.EntityNotFoundException: Unable to find support.hibernate.entity.Plan with id 1234
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:145)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
    ...
    at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.intercept(LazyAttributeLoadingInterceptor.java:61)
    at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.readObject(LazyAttributeLoadingInterceptor.java:296)
    at support.hibernate.entity.Employee.$$_hibernate_read_plan(Employee.java)
    at support.hibernate.entity.Employee.getPlan(Employee.java:50)
        ...
    

Environment

  • Red Hat JBoss Enterprise Application Platform (EAP) 7.1
  • Hibernate 5.1

Subscriber exclusive content

A Red Hat subscription provides unlimited access to our knowledgebase, tools, and much more.

Current Customers and Partners

Log in for full access

Log In

New to Red Hat?

Learn more about Red Hat subscriptions

Using a Red Hat product through a public cloud?

How to access this content