如何在使用基本实体和派生实体时使用Hibernate注释有不同的列来映射?

时间:2017-05-13 00:54:45

标签: hibernate annotations

我在上面阅读了这个问题: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”。如何为基本实体中的id列配置映射,以便它映射到派生实体中的不同列?

1 个答案:

答案 0 :(得分: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;
}

在您希望单个实现但具有相同结构的不同数据库表示的地方非常有用。