Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA MappedSuperclass with ManyToOne

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.

like image 988
zdenda.online Avatar asked Oct 22 '25 00:10

zdenda.online


1 Answers

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.

like image 157
Ali BEN AMOR Avatar answered Oct 27 '25 05:10

Ali BEN AMOR