I am creating a billing system它为每个客户管理一个分类帐。每个 Ledger 都有一个 LedgerEntry 列表,记录每个客户交易。
当我测试这个时,我注意到,如果我在同一事务中创建了一堆 LedgerEntry,@Id 值并不是为了将对象赋予 em.persist(),除非我在创建每个条目后执行了 em.flush()。
因为我依赖 id 的顺序来实现 Ledger 的正确行为(具体来说,当前余额是列表中的最后一个 LedgerEntry —— 由 @OrderBy "id ASC"强制执行),这意味着我必须刷新()很多次。
有没有办法避免在创建每行后刷新?也就是说,在不使用 @OrderColumn 的情况下对对象的持久化方式进行某种排序?
最佳答案
我不确定这是通用 JPA 还是仅限 Hibernate,但请注意 Hibernate 的 persist()
和 save()
之间的区别。来自 the docs (强调我的):
persist()
makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.- save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction.
因此,如果您使用 save()
,则应按照您调用 save()
的顺序生成 ID。如果仅仅为了获取 ID 进行插入会出现问题(出于性能等原因),您可以选择使用另一个不需要访问数据库的 ID 生成器。
关于java - JPA:我可以强制将对象按照对象发送到 persist() 的顺序持久化到数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792035/