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

查看:86
本文介绍了在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提供程序将数据库操作延迟到将提交事务的时间.

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生成器不必点击数据库即可获取ID值.他们使用allocationSize参数向DB TABLE或SEQUENCE请求ID的 batch ,这些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天全站免登陆