JPA MappedSuperclass 与 ManyToOne

zde*_*ine 5 entity jpa mappedsuperclass

我面临着一个典型的问题。想象一下对象之间典型的 1-N 关系。准确地说,用户(U)和房间(R):[U]*---1[R]。

问题来了,Room 应该是带有实现的抽象基类,例如 BlueRoom、RedRoom。如何正确设置用户实体内的关系?

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
}
Run Code Online (Sandbox Code Playgroud)

我知道这可能可以通过在 RoomSuperclass 上使用 @Entity 而不是 @MappedSuperclass 来解决,但我不确定这是否是一个好的解决方案以及是否有更好的解决方案。

zde*_*ine 0

根据帖子下的评论。将超类声明为 @Entity 是解决方案。

  • 我想知道同样该死的事情。我用头撞墙半天试图使用这个注释,因为我不想将我的抽象实体映射到表中!!!!这是抽象的!但是不,如果我想使用继承,我必须指定一个映射实体,那么这个 annot 是做什么用的? (3认同)
  • **实体不能同时使用@Entity 和@MappedSuperclass 进行注释**。 (3认同)