此内容没有您所选择的语言版本。

3.2.6. Mapping composite primary and foreign keys


Composite primary keys use a embedded class as the primary key representation, so you'd use the @Id and @Embeddable annotations. Alternatively, you can use the @EmbeddedId annotation. Note that the dependent class has to be serializable and implements equals()/hashCode(). You can also use @IdClass as described in Section 3.2.3, “Mapping identifier properties”.
@Entity
public class RegionalArticle implements Serializable {

    @Id
    public RegionalArticlePk getPk() { ... }
}

@Embeddable
public class RegionalArticlePk implements Serializable { ... }
Copy to Clipboard Toggle word wrap
or alternatively
@Entity public class RegionalArticle implements Serializable {

    @EmbeddedId
    public RegionalArticlePk getPk() { ... }
}

public class RegionalArticlePk implements Serializable { ... }
Copy to Clipboard Toggle word wrap
@Embeddable inherit the access type of its owning entity unless the Hibernate specific annotation @AccessType is used. Composite foreign keys (if not using the default sensitive values) are defined on associations using the @JoinColumns element, which is basically an array of @JoinColumn. It is considered a good practice to express referencedColumnNames explicitly. Otherwise, Hibernate will suppose that you use the same order of columns as in the primary key declaration.
@Entity
public class Parent implements Serializable {
    @Id
    public ParentPk id;
    public int age;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumns ({
        @JoinColumn(name="parentCivility", referencedColumnName = "isMale"),
        @JoinColumn(name="parentLastName", referencedColumnName = "lastName"),
        @JoinColumn(name="parentFirstName", referencedColumnName = "firstName")
    })
    public Set<Child> children; //unidirectional
    ...
}
Copy to Clipboard Toggle word wrap
@Entity
public class Child implements Serializable {
    @Id @GeneratedValue
    public Integer id;

    @ManyToOne
    @JoinColumns ({
        @JoinColumn(name="parentCivility", referencedColumnName = "isMale"),
        @JoinColumn(name="parentLastName", referencedColumnName = "lastName"),
        @JoinColumn(name="parentFirstName", referencedColumnName = "firstName")
    })
    public Parent parent; //unidirectional
}
Copy to Clipboard Toggle word wrap
@Embeddable
public class ParentPk implements Serializable {
    String firstName;
    String lastName;
    ...
}
Copy to Clipboard Toggle word wrap
Note the explicit usage of the referencedColumnName.
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat