5

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.

zdenda.online
  • 2,451
  • 3
  • 23
  • 45
  • 1
    Yes, that's the solution. If you have an association to something, then this something must be an entity. – JB Nizet Jan 07 '12 at 20:11
  • Thanks for a reply JB, I will wait day, two if someone else replies and then close the question – zdenda.online Jan 07 '12 at 20:24
  • Possible duplicate of [@MappedSuperclass is not an @entity?](https://stackoverflow.com/questions/36991236/mappedsuperclass-is-not-an-entity) – Yassir Khaldi Apr 16 '18 at 16:54

2 Answers2

1

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.

Ali BEN AMOR
  • 126
  • 1
  • 6
0

According to commentaries under the post. Declaring superclass as @Entity is the solution.

zdenda.online
  • 2,451
  • 3
  • 23
  • 45
  • Could you explain for what purpose there's @MappedSuperclass ? – salocinx Sep 18 '15 at 15:38
  • 3
    I'm wondering the exact same damn thing. I'm banging my head against the wall for half a day trying to use this annot because I don't want to map my abstract entity into a Table !!!! It's ABSTRACT ! but no, if I want to use inheritance, I have to specify a mapped entity, so what is this annot made for ?? – Alex Feb 16 '17 at 10:12
  • 3
    **An entity cannot be annotated with both @Entity and @MappedSuperclass**. – Mehraj Malik Oct 15 '18 at 10:32