在 JPA/Play 中提交事务之前,实体如何获取 ID? [英] How does an entity get an ID before a transaction is committed in JPA/Play?

查看:24
本文介绍了在 JPA/Play 中提交事务之前,实体如何获取 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到这个问题.

事实证明,即使不手动提交事务,在提交TX之前,调用save()方法后,此人就有了ID.

It turns out that even without committing the transaction manually, before the TX is committed, the person has an ID after calling the save() method.

数据库不负责分配 ID 字段吗?如果是这样,如何在提交前填写 ID 字段?在提交 TX 之前是否与 DB 进行任何通信?

Isn't the database responsible of assinging the ID field? If so, how can the ID field be filled before commit? Does any communication with the DB occur before the TX is committed?

推荐答案

是的,JPA 允许在事务提交之前与 DB 通信.它可能发生,即当您显式调用 EntityManager#flush() 时.

Yes, the JPA is allowed to communicate with the DB before transaction commit. It can occur i.e. when you explicitly invoke EntityManager#flush().

此外,只要认为有必要,JPA 提供程序就可以执行刷新操作.但是,为了方便起见,JPA 提供程序将 DB 操作延迟到事务提交的时间.

Moreover, the JPA provider is allowed to do the flush operation whenever it feels it's necessary. However, by the convenience, JPA providers delays DB operations to the time the transaction will be committed.

某些自动 ID 生成器策略必须访问数据库才能获取 PK 值(据我所知,IDENTITY 策略就是这样工作的).
相反,TABLESEQUENCE 生成器不需要点击 DB 来获取 ID 值.他们使用 allocationSize 参数向 DB TABLE 或 SEQUENCE 请求 batch 的 ID,这些 ID 将在不与数据库进一步通信的情况下提供给新实体.

Some automatic ID generator strategies must hit the database to get the PK value (as far as I remember the IDENTITY strategy works that way).
As a contrary, the TABLE or SEQUENCE generators don't necessary need to hit the DB to get the ID value. They use the allocationSize parameter to ask the DB TABLE or SEQUENCE for a batch of IDs that will be given to new entities without further communication with the database.

这篇关于在 JPA/Play 中提交事务之前,实体如何获取 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆