Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does hibernate populate ids of auto generated fields?

Say i have an entity with an auto generated primary key. Now if i try to save the entity with values of all other fields which may not be unique. The entity gets auto populated with the id of the row got inserted. How did it get hold of that primary key value?

EDIT:

If the primary key column is say identity column whose value is totally decided by the database. So it does an insert statement without that column value and the db decides the value to use does it communicate back its decision (I dont think so)

like image 341
vinothkr Avatar asked Jun 07 '11 08:06

vinothkr


People also ask

How get ID after save in hibernate?

@Id @GeneratedValue(strategy = GenerationType. IDENTITY) @Column(name = "id") private int id; Now when you save the object, you can get the Id using the getter method that you set for id. In this case, the return type of save() method must be Integer or int .

How does Hibernate generate primary key?

IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key, SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence.

What is primary key in hibernate annotation?

Mapping a primary key column with JPA and Hibernate is simple. You just need to add an attribute to your entity, make sure that its type and name match the database column, annotate it with @Column and you're done.


2 Answers

Hibernate use three method for extracting the DB auto generated field depending on what is support by the jdbc driver or the dialect you are using.

Hibernate extract generated field value to put it back in the pojo :

  1. Using the method Statement.getGeneratedKeys (Statement javadocs)

    or

  2. Inserting and selecting the generated field value directly from the insert statement. (Dialect Javadocs)

    or

  3. Executing a select statement after the insert to retrieve the generated IDENTITY value

All this is done internally by hibernate.

Hope it`s the explication you are looking for.

like image 194
Joel Hudon Avatar answered Sep 28 '22 00:09

Joel Hudon


This section of the Hibernate documentation describes the auto generation of ids. Usually the AUTO generation strategy is used for maximum portability and assuming that you use Annotations to provide your domain metadata you can configure it as follows:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

Anyway the supplied link should provide all the detail you need on generated ids.

like image 31
Alex Barnes Avatar answered Sep 28 '22 01:09

Alex Barnes