简体   繁体   English

JPA 和 Hibernate 中的 @Id 注释

[英]@Id annotation in JPA and Hibernate

If I don't want to automatically generate the primary Key, instead, I want to supply the ID with the first column of the table as primary key.如果我不想自动生成主键,相反,我想提供带有表第一列的 ID 作为主键。

2 A
4 B
7 D
13 E

... ...

I want the first column 2,4, 7, 13 to be the primary key of the table.我希望第一列 2,4,7,13 成为表的主键。 Should I just use @Id to do the annotation?我应该只使用@Id 来做注释吗?

@Entity
public class Code {
   @Id
   @Column(unique=true)
   private int id;

   ...
}

Or, if @Id is used, the primary key will be always automatically generated, instead of using the first column, in this case?或者,如果使用@Id,在这种情况下,将始终自动生成主键,而不是使用第一列?

@Id will only declare the primary key. @Id只会声明主键。 it will not insert generated value.它不会插入生成的值。 if you use @GeneratedValue then it will generate the value of the field.如果您使用@GeneratedValue那么它将生成该字段的值。

An object id (OID) is something that uniquely identifies an object . object id (OID)是唯一标识object东西。 Within a VM this is typically the object's pointer.VM这通常是object's指针。 In a relational database table , a row is uniquely identified in its table by its primary key .在关系database table ,行在其表中由其primary key唯一标识。

When persisting objects to a database you need a unique identifier for the objects , this allows you to query the object , define relationships to the object , and update and delete the object .当持久objects到你需要的唯一标识符的数据库objects ,这可以让你查询的object ,定义relationshipsobject ,并更新和删除的object In JPA the object id is defined through the @Id annotation and should correspond to the primary key of the object's table.JPA ,对象 id 是通过@Id注释定义的,并且应该对应于object's表的primary key

An object id can either be a natural id or a generated id. object id可以是自然 id 或生成的 id。 A natural id is one that occurs in the object and has some meaning in the application.自然 ID 是出现在object并在应用程序中具有某种意义的 ID。 Examples of natural ids include email addresses, phone numbers, and social insurance numbers.自然 ID 的示例包括电子邮件地址、电话号码和社会保险号码。 A generated id (also known as a surrogate id) is one that is generated by the system.生成的 ID(也称为代理 ID)是由系统生成的 ID。

In JPA an @Id can be easily assigned a generated sequence number through the @GeneratedValue annotation.JPA ,可以通过@GeneratedValue注释轻松地为@Id分配生成的序列号。

如果您总是手动为您的实体提供主键值,那么@Id注释就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM