Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embeddable abstract class with JPA (+Hibernate)

I am trying to implement this JPA model:

  • Class Owner is an Entity. It has @Embedded instance of class AbstractParent.
  • Class AbstractParent is @Embeddable. It is an abstract class, and this class has two children.The children are concrete classes.

The exception is: Cannot instantiate abstract class or interface: AbstractParent

It seems that (1) I need component inheritance, but (2) component inheritance is not allowed in JPA and (3) it was not implemented in Hibernate. Could you confirm that (1), (2) and (3) are correct? If they are correct could you provide any advice or workaround? I use hibernate-jpa 2.0, hibernate-core 3.5.1, hibernate-core-annotations 3.2.0

like image 522
Kosta Avatar asked Oct 14 '25 20:10

Kosta


1 Answers

To answer questions why one may need this implementation: here is an example. Database table has information about computers, computers have monitors, if monitor is LCD then it's parameter is "pixels". If monitor is a TV then it's parameter is "lines". All monitors also have parameter "weight" Data structure of this table includes: id, RAM, monitor_indicator, weight, lines, pixels.

This data structure can be implemented in classes:

  • Class Computer {id, RAM, display}
    • It has information about computers.
  • Abstract class AbstractDisplay {weight}
    • It has generic information about displays.
  • Class LCDDisplay {pixels} inherits class AbstractDisplay
    • it has LCD specific information (pixels).
  • Class TVDisplay {lines} inherits class AbstractDisplay
    • it has TV specific information (lines).

The basic idea is that main class (Owner/Computer) embeds another class (Parent/AbstractDisplay) that can have different set of parameters depending on type of the embedded class.

Regarding how embedded abstract class can be instantiated: same way as an abstract class is instantiated now in JPA: in the above example "monitor_indicator" indicates children class that should be used, this field must exist during the time when class Computer is instantiated.

like image 159
Kosta Avatar answered Oct 17 '25 09:10

Kosta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!