【问题标题】:How to use Hibernate annotation while using base entity and derived entities have different columns to map?如何在使用基本实体和派生实体有不同的列来映射时使用 Hibernate 注释?
【发布时间】:2017-10-12 09:24:08
【问题描述】:

我读到了这个问题:Hibernate Annotation using base entity

它提到了将@MappedSuperclass 与@Id 一起使用。

@MappedSuperclass
class BaseEntity {
    @Id
    private int id;
    //getters and setters.
}

@Entity
class Movie extends BaseEntity {
    @Column
    private String name;
    @Column
    private int year;
    @Column
    private int durationMins;
    //getters and setters
}

但是,如果我有多个派生实体扩展 BaseEntity 并且派生实体表对基实体中定义的列具有不同的列名,该怎么办?例如:

@Entity
@Table(name = "A")
class A extends BaseEntity {
}

@Entity
@Table(name = "B")
class B extends BaseEntity {
}

而在表 A 中,id 列称为“A_id”,而在表 B 中,id 列称为“B_id”。如何配置 baseentity 中 id 列的映射,使其映射到派生实体中的不同列?

【问题讨论】:

    标签: hibernate annotations


    【解决方案1】:

    您可能希望在此处使用AttributeOverride 来基本上强制执行与相关实体类相关的特定语义。

    @Entity
    @Table(name = "A")
    @AttributeOverride(name = "id", @Column(name = "a_id"))
    public class A extends BaseEntity {
    }
    
    @Entity
    @Table(name = "B")
    @AttributeOverride(name = "id", @Column(name = "b_id"))
    public class B extends BaseEntity {
    }
    

    使用AttributeOverride 通常会发现的真正好处是定义@Embeddable 注释类的概念。例如:

    @Embeddable
    public class StockingDetails {
      private Integer minQuantity;
      private Integer maxQuantity;
      // other attributes
    }
    
    @Entity
    public class Product {
      // other attributes 
      @Embedded
      @AttributeAssociations({
        @AttributeOverride(name = "minQuantity", column = @Column(name = "some_min")),
        @AttributeOverride(name = "maxQuantity", column = @Column(name = "some_max"))
      })
      private StockingDetails someTypeOfDetails;
      @Embedded
      @AttributeAssociations({
        @AttributeOverride(name = "minQuantity", column = @Column(name = "other_min")),
        @AttributeOverride(name = "maxQuantity", column = @Column(name = "other_max"))
      })
      private StockingDetails otherDetails;
    }
    

    当您想要一个实现但具有相同结构的不同数据库表示时,它非常有用。

    【讨论】:

    • 哇,这真是我要找的东西!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-09-20
    • 2016-08-05
    • 2018-12-10
    • 1970-01-01
    • 2016-02-14
    • 2018-04-29
    • 2017-02-11
    • 2015-04-11
    相关资源
    最近更新 更多