问题描述
我在使用Hibernate javax.persistence.SequenceGenerator.allocationSize()属性时遇到问题.如果将其设置为1,则在向数据库中插入大量记录时会遇到性能问题.否则,当我将其设置为默认值(50)或更高的值时,会收到带有指定标识符的实体已存在的异常消息!
I have an issue using Hibernate javax.persistence.SequenceGenerator.allocationSize() property. When it is set to 1 I face performance issues when inserting a lot of records to database. Otherwise when I set it to default (50) or even higher value I receive exceptions that entity with specified identifier is alredy exists!
最大的问题是,许多开发人员使用共享数据库,因此生成的标识符确实有可能不会同步.
The biggest problem is that a lot of developers use shared database, so it is really possible that generated identifiers will not be synchronized.
另一方面,我注意到使用"INCREMENT BY 1"创建的Oracle序列.可以将其相应地设置为allocationSize可以解决问题?
At other hand I noticed that Oracle sequence created using "INCREMENT BY 1". May be setting this accordingly to allocationSize can solve the problem?
我正在使用WildFly 10.1(因此Hibernate版本是5.0.10)和Oracle 12c(12.2.0.1).
I am using WildFly 10.1 (so Hibernate version is 5.0.10) and Oracle 12c (12.2.0.1).
提前感谢您的建议!
推荐答案
是的,SequenceGenerator
的allocationSize
的值以及数据库递增序列的步骤必须相同.
Yes, the value of the allocationSize
of your SequenceGenerator
and the steps in which your database increments the sequence have to be identical.
如果将allocationSize
属性设置为50,则告诉Hibernate该序列递增50,并且在从序列中选择下一个值之前,它将在内部生成49个值.
If you set the allocationSize
attribute to 50, you tell Hibernate that the sequence gets incremented by 50 and that it shall generate 49 values internally before it selects the next value from the sequence.
如果您将allocationSize
和序列的增量保持同步,则不必担心重复的ID.
And you don't need to worry about duplicate ids if you keep the allocationSize
and the increment of the sequence in sync.
说吧;您有2台服务器连接到同一数据库.两台服务器的allocationSize
均为50,并且您已将数据库序列配置为增加50.
Let's say; you have 2 servers which connect to the same database. Both servers use an allocationSize
of 50, and you configured your database sequence to be incremented by 50.
Server1从序列中请求一个新值,并获得1000.它将在内部存储该值并将其递增,直到达到1049.
Server1 request a new value from the sequence and gets 1000. It will store this value internally and increment it until it reaches 1049.
与此同时,Server2从序列中请求一个新值并获得1050.它将将该值递增直到1099.
In the meantime, Server2 requests a new value from the sequence and gets 1050. It will increment this value until 1099.
数据库序列返回的下一个值将是1100.如您所见,不会有重复的ID.但是主键值之间可能存在间隙,因此您不能使用它们按时间顺序对数据库记录进行排序.但是无论如何,您都不应该为此使用主键...
The next value returned by the database sequence will be 1100. As you can see, there will be no duplicate ids. But there might be gaps between the primary key values, and you can't use them to order your database records chronologically. But you shouldn't use primary keys for that anyways ...
这篇关于javax.persistence.SequenceGenerator.allocationSize()是否应与INCREMENT BY一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!