【问题标题】:Composite key without @EmbeddedId没有@EmbeddedId 的复合键
【发布时间】:2012-07-14 02:40:48
【问题描述】:

有没有办法在 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
}

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

【问题讨论】:

  • 您可以只使用多个@Id 属性。我下面的回答对你有用吗?

标签: hibernate annotations composite-primary-key


【解决方案1】:

下面hibernatedoc的第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;
}

【讨论】:

  • 感谢您的回答,您必须注意 Customer 实体必须实现 Serializable 因为它具有复合键。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 2021-10-28
相关资源
最近更新 更多