Reputation: 1959
I have those jpa Entities
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
class AbstarctAddress {
}
@Entity
public class ConsolidationHub extends AbstarctAddress {
}
@Entity
class Transport {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "delivery_address_id")
private AbstarctAddress address;
}
when I am doing
select t from Transport t left join fetch t.address
and then instanceof check like this
t.getAddress() instanceOf ConsolidationHub it returns false
. This is because I got hibernate proxy. when I change to EAGER I don't have that problem. but I don't want to put EAGER since I have performance problems with EAGER.
Do you know how it is possible to solve this issue?
PS. I know that instanceOf check is bad practice, I just need to maintain old code in which there are lots of instanceOf checks and I cannot refactor all of them now.
Upvotes: 4
Views: 686
Reputation: 10716
I'm afraid the answer is: start writing OOP code. instanceof
flies in the face of polymorphism. The clients of a class should never care which specific subtype/implementation they are talking to.
If you used entity inheritance, and now need to use instanceof
in your code, your design is most probably flawed. Hibernate uses proxies on many occasions, and you cannnot rely on instanceof
or .getClass()
always returning the exact class of your entity.
If, on the other hand, you've used instanceof
out of curiosity, and were surprised to find that it actually returns false
, fear not, all calls you make to this entity proxy are still polymorphic.
The reason why instanceof
fails here is that Hibernate needs to initialize the lazy property with something, and it cannot determine the type of that something until the property is loaded. If you insist on using instanceof
, you may try enabling entity enhancement.
Upvotes: 2