JPA中的MappedSuperclass和ManyToOne

5

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

问题来了,Room应该是一个抽象基类,有BlueRoom、RedRoom等实现。如何在User实体内正确设置关系呢?

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
}

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

1
是的,那就是解决方案。如果您与某个东西有关联,那么这个东西必须是一个实体。 - JB Nizet
谢谢您的回复JB,我会等一天或两天看看是否有其他人回答,然后关闭问题。 - zdenda.online
可能是[@MappedSuperclass不是@Entity?]的重复问题(https://dev59.com/HVoU5IYBdhLWcg3w5pya)。 - Yassir Khaldi
2个回答

1
一个被注解为MappedSuperclass的超类不应该被注解为Entity
关系注解只能用于被注解为Entity的类。
你可以将MappedSuperclass注解替换为Inheritance(strategy = InheritanceType.TABLE_PER_CLASS),并在你的超类上添加Entity注解。
这样,Hibernate将为每个类创建一个数据库表。还有其他策略可以在官方文档中查看。

JOINED 一种策略,其中特定于子类的字段被映射到与父类不同的表中,并执行连接以实例化子类。

SINGLE_TABLE 每个类层次结构一个表。

TABLE_PER_CLASS 每个具体实体类一个表。


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

你能解释一下 @MappedSuperclass 的作用是什么吗? - salocinx
3
我也在想完全相同的事情。我已经试了半天使用这个注释,因为我不想将我的抽象实体映射到表格中,我现在都快敲墙了!它是抽象的,但是如果我想使用继承,就必须指定一个映射实体,那么这个注释到底有什么用? - Alex
3
一个实体不能同时使用 @Entity 和 @MappedSuperclass 进行注释。 - Mehraj Malik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接