user697911
user697911

Reputation: 10531

@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.

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. Should I just use @Id to do the annotation?

@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?

Upvotes: 8

Views: 16831

Answers (3)

Thomas Naskali
Thomas Naskali

Reputation: 581

If you always manually provide the primary key value for your entities, then the @Id annotation is enough.

Upvotes: 0

Sai prateek
Sai prateek

Reputation: 11896

An object id (OID) is something that uniquely identifies an object. Within a VM this is typically the object's pointer. In a relational database table, a row is uniquely identified in its table by its 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. In JPA the object id is defined through the @Id annotation and should correspond to the primary key of the object's table.

An object id can either be a natural id or a generated id. A natural id is one that occurs in the object and has some meaning in the application. Examples of natural ids include email addresses, phone numbers, and social insurance numbers. A generated id (also known as a surrogate id) is one that is generated by the system.

In JPA an @Id can be easily assigned a generated sequence number through the @GeneratedValue annotation.

Upvotes: 0

stinepike
stinepike

Reputation: 54672

@Id will only declare the primary key. it will not insert generated value. if you use @GeneratedValue then it will generate the value of the field.

Upvotes: 4

Related Questions