Hibernate Inheritance - Getting superclass instance and casting into subclass

后端 未结 1 798
萌比男神i
萌比男神i 2021-02-06 06:47

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

1条回答
  •  独厮守ぢ
    2021-02-06 07:22

    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.

    0 讨论(0)
提交回复
热议问题