I'm facing kind of typical issue. Imagine typical 1-N relationship between objects. To be precise User(U) and Room(R): [U]*---1[R].
Here comes the problem, Room should be abstract base class with implementations for example BlueRoom, RedRoom. How correctly set relationship within User entity?
public interface Room { ... }
@MappedSuperclass
public abstract class RoomSuperclass implements Room { ... }
@Entity
public class BlueRoom extends RoomSuperclass { ... }
@Entity
public class RedRoom extends RoomSuperclass { ... }
@Entity
public class User {
@ManyToOne(targetEntity = ???) // I don't know if it will be BlueRoom or RedRoom
private Room room; // ManyToOne cannot be applied on mapped superclass
}
I know this could be probably solved by using @Entity on RoomSuperclass instead of @MappedSuperclass but I'm not sure if it is good solution and if there is any better one.
A super class annotated with the MappedSuperclass should not be annotated with Entity.
Relation annotations can only be used with a class annotated with Entity.
You can replace the MappedSuperclass annotation with Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) and add the Entity annotation to your super class.
This way hibernate will create a database table for each class. there is other strategies that you can check out in the official docs.
JOINED A strategy in which fields that are specific to a subclass are mapped to a separate table than the fields that are common to the parent class, and a join is performed to instantiate the subclass.
SINGLE_TABLE A single table per class hierarchy.
TABLE_PER_CLASS A table per concrete entity class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With