Consider this scenario.
There are plots, some are residential plots and some are commercial plots.
There are also owners. But an owner can buy only a plot and it
You're not using polymorphism, and it hurts even more in a JPA environment.
The reason you observe this behavior is because of the usage of proxies by Hibernate. When Hibernate loads an Owner, it can't tell if the plot is a commercial or residential plot. It would have to do an additional query to know it. So it initializes the plot field with a lazy proxy, which is an instance of a dynamically generated class which extends Plot, but is neither a CommercialPlot nor a ResidentialPlot.
When a method is called on the proxy, the proxy initializes itself by getting the Plot data from the database, and it delegates to an instance of CommercialPlot or ResidentialPlot.
The solution is to use ploymorphism. Add an abstract method to the Plot class (getType()
, or isResidential()
, for example), and implement it in both subclasses. If that isn't possible because you need business logic that depends on the entity type but shouldn't be in the entity itself, use the visitor pattern.
I wrote a blog article on this subject if you need more details, but it's in French. Maybe Google Translate could help you.