1

有没有办法在 Hibernate 中创建带有注释的复合键,而无需创建新的 PK 类(即@EmbeddedId)?

我的问题是,我有一个具有许多属性的抽象类 CommonClass,我需要为许多实体类继承它。每个类都有不同类型的 id,但它们都需要是具有 CommonClass 属性的复合键。例子:

@MappedSuperclass
abstract class CommonClass {
    @Id
    int typed;

    int a0;
    int a1;
    //many other attributes
}

@Entity
class EntityString extends CommonClass {
    @Id
    String id;
    //ID need to be id+typed from CommonClass

    //other attributes
}

@Entity
class EntityInteger extends CommonClass {
    @Id
    Integer id;
    //ID need to be id+typed from CommonClass

    //other attributes
}

那么,最好的方法是什么?

4

1 回答 1

2

以下休眠文档的第 2.2.3.2.2 节。

另一种可以说更自然的方法是将@Id 放置在我的实体的多个属性上。这种方法仅受 Hibernate 支持,但不需要额外的可嵌入组件。

@Entity
class Customer implements Serializable {
  @Id @OneToOne
  @JoinColumns({
    @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
    @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
  })
  User user;

  @Id String customerNumber;

  boolean preferredCustomer;
}

@Entity 
class User {
  @EmbeddedId UserId id;
  Integer age;
}

@Embeddable
class UserId implements Serializable {
  String firstName;
  String lastName;
}
于 2012-07-13T18:40:48.307 回答