开发者

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开发者_JAVA百科 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)


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.


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.


When you create an object with the, say, sequence-derived surrogate primary key, you pass it to the Hibernate session with that field set to the value that Hibernate interprets as "not assigned", by default 0. This field is not populated with the assigned value until the corresponding record is not inserted into the database table. You can trigger insertion by either explicitly calling flush() on the hibernate session or performing a database read in the same session. After that you can check the value of that field and it will be assigned rather than 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜