4

我决定使用满足以下要求的 Hibernate id 生成器: - 当从不同的应用程序(不同的 JVM)访问域时安全 id 生成 - 使用 id 间隔(每次新 ID 时不要查询数据库需要)

经过一些调查,我选择了 2 个休眠增强标识符生成器之一,它是

org.hibernate.id.enhanced.TableGenerator

问题是该算法在数据库中保留的不是下一个可用值,而是下一个可用间隔的结束,所以,假设我有一个 increment_size 为 10 的 id 生成器,当我请求一个 id 时,我收到间隔 1 - 10,但现在在数据库中存储的不是值 11,而是 21。通过这种行为,我必须在映射到特定表的所有类中保持 increment_size 相同。为什么会有这种行为?有没有什么办法解决这一问题 ?

4

2 回答 2

4

org.hibernate.id.enhanced.TableGenerator 定义了一个能够同时生成多个值的表。听起来您试图让它从多个实体的单个值生成标识符。如果您想利用它,这由 'segment_value' TableGenerator 配置设置控制。

至于价值观,没有什么可以“修复”的。它没有坏。如果您想要不同的行为,请配置不同的行为。这由称为优化器的东西控制,由 TableGenerator 的“优化器”配置设置定义。这在手册中都有介绍:http ://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#mapping-declaration-id 具体参见“5.1.2.3.增强标识符生成器”部分”和“5.1.2.3.1。标识符生成器优化”。该手册并未讨论所有可用的优化器。听起来你想要的那个叫做“pooled-lo”,就像“pooled”一样,但存储的是 lo 值而不是高值。

于 2012-07-09T19:04:19.260 回答
1

This post is old but for others that may have the same kind of problem.

As indicated by Steve Ebersole, you should used "pooled-lo" optimizer in your case. Check also your hibernate version, it should be >= 4.3.11 because there was an issue in previous versions.

To give some explanation, with pooled-lo optimizer, the value stored in the database is the low value of the next interval available.

So if the id of the last entity persisted is in [1;10], the next interval available is [11,20] and the value stored in database will be 11, as you were expecting.

Thus if you have another program that don't use hibernate and is not even aware of the increment size defined in hibernate configuration, it will still be able to insert entities without breaking the sequence.

All it will have to do is to atomically get the sequence value and increment it, and then use the value retrieve (before the "incrementation") as the new entity id it wants to insert. In our example in order to insert one line, it will update the sequence value to 12 and add the new entity with the id 11. Thus when hibernate will reach the last id of its current interval in memory (10), it will query the database and store the value 22 in order to keep for it self the new interval of id [12;21].

于 2017-01-22T15:38:35.113 回答