java 如何分配多个字段作为实体的主键(使用 JPA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16947162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:28:18  来源:igfitidea点击:

How to assign several fields as a primary key of an entity (using JPA)

javajpaorm

提问by sheidaei

One can assign a primary key for its class by using @Id annotation in JPA. My question is what if one doesn't want to have an auto generated key in his tables and use fields (maybe more than one) as a primary key.

可以通过在 JPA 中使用 @Id 注释为其类分配主键。我的问题是,如果一个人不想在他的表中使用自动生成的键并使用字段(可能不止一个)作为主键,该怎么办。

Let's say we have a person table with SSN, NATIONALITY and NAME. SSN is defined as the number a person is identified by in his country. Thus, we might have two persons with the same number in two different countries. The primary key for this table can be SSN+NATIONALITY. Is there any way to map these two fields using JPA and map it to an object? or the only way it to create an auto generated id and use @Id annotation

假设我们有一个带有 SSN、NATIONALITY 和 NAME 的 person 表。SSN 被定义为一个人在他的国家被识别的号码。因此,我们可能在两个不同的国家有两个相同号码的人。此表的主键可以是 SSN+NATIONALITY。有没有办法使用JPA映射这两个字段并将其映射到对象?或创建自动生成的 id 并使用 @Id 注释的唯一方法

CREATE TABLE PERSON (
     SSN   INT,
     NATIONALITY VARCHAR,
     NAME VARCHAR
  )

回答by michal

Yes, it is possible. A composite primary key consist of multiple primary key fields. Each primary key field must be one of the supported by JPA type. For your table, you have:

对的,这是可能的。复合主键由多个主键字段组成。每个主键字段必须是 JPA 类型支持的字段之一。对于您的表,您有:

@Entity @IdClass(PersonId.class)
public class Person {
    @Id int ssn;
    @Id String nationality;
     ....
}

For entity with multiple key, JPA requires defining a special ID class. This class should be attached to the entity class using the @IdClass annotation.

对于具有多个键的实体,JPA 需要定义一个特殊的 ID 类。此类应使用@IdClass 注释附加到实体类。

class PersonId {
    int ssn;
    String nationality;
}

The ID class reflects the primary key fields and its objects can represent primary key values

ID 类反映主键字段,其对象可以表示主键值