0

Some JPA provider like Hibernate uses Proxy to handle lazy initialization. Consider the following example:

@Entity
public class Person {
     @Id
     private Long id;

     @ManyToOne(fetch=FetchType.LAZY)
     private House house;
}

@Entity
public class House {
    @Id
    private Long id;

    @Embedded
    private Address address;

}

When fetching a Person entity, its house property is set to a Proxy (lazy).

Person person = em.find(Person.class, 1);
House house = person.getHouse();  // Proxy
if (house == null)
   System.out.println("has no house);
else
   System.out.println("has a house");

If the person does not have a house, the person object has a Proxy of house (not null). The code above will print wrong message. Is this an issue for JPA proxy?

Sunnyday
  • 2,252
  • 1
  • 17
  • 46
  • 1
    It is an issue for the JPA provider if it is the type that returns a proxy from that operation. If on the other hand the JPA provider does not return proxies (e.g DataNucleus), then it is not a problem. –  Jan 10 '18 at 07:09

1 Answers1

0

As a matter of fact, I'm surprised you're facing this issue. According to this question: Making a OneToOne-relation lazy, lazy optional many-to-one associations should work just fine; it is the one-to-one associations that cause problems. The issue here is that without enhancement, Hibernate cannot automagically turn the proxy into a null reference. Are you actually seeing this behavior in Hibernate?

In any case, you should be able to resolve the issue by enabling enhancement. This way, Hibernate is able to overwrite the getter method to return null if the initialized proxy does not represent a valid House. Not sure how the issue is resolved by other providers, though.

crizzis
  • 7,901
  • 2
  • 22
  • 36