【问题标题】:Have attributes from one-to-one mapped entity具有来自一对一映射实体的属性
【发布时间】:2019-04-23 10:31:27
【问题描述】:

如何在拥有实体中包含一对一映射实体属性的部分(或全部)属性。

我已经创建了一个例子来考虑这个问题:

@Data // Lombok's to contain all getter and setters
@Entity
@Table(name = "room")
public class Room {

    @Column
    int length;

    @Column
    int breadth;
}

@Data // Lombok's to contain all getter and setters
@Entity
@Table(name = "dance_room")
public class DanceRoom {

    @Column
    int numberOfPeople;

    @OneToOne
    Room room;
}

现在我希望 DanceRoom 实体在这个实体中也有 length 属性,但它们不应该在 dance_room 数据库表中。

我认为的直接解决方案是:

@Data // Lombok's to contain all getter and setters
@Entity
@Table(name = "dance_room")
public class DanceRoom {

    @Column
    int numberOfPeople;

    @OneToOne
    Room room;

    public int getLength() {
        return room.length;
    }

}

是否可以在DanceRoom JPA 实体中创建这些属性并将列保存在room 数据库表中?

或者有没有其他方法可以创建这样的映射?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    从实体名称和访问数据的方式,我建议使用 Inheritance

    有人会争辩说关系数据库没有继承。没错,但是 JPA 和 ORM 工具通常允许我们将这些关系映射到数据库。

    JPA inheritence strategies.

    只需将 Room 实体设为 DanceRoom 实体的,按照之前的链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2021-04-03
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多