javax.persistence.EntityExistsException with SequenceGenerator

戏子无情 提交于 2019-12-02 03:46:07

allocationSize parameter must match the INCREMENT BY value of the sequence.

It works in such a way that Hibernate gets a value from the sequence (from the database), and then keeps that value in the memory and generates next X subsequent identifiers (where X=allocationSize) incrementing this value by 1 in the memory, without reaching for the database.

Once Hibernate generates X identifiers, it gets the next value from the sequence, and generates new X identifiers, incrementing that value by 1


A simple example - let say that:

  • @SequenceGenerator( ....allocationSize=5 ...)
  • CREATE SEQUENCE .... INCREMENT BY 1 ...

In the above case Hibernate:

  1. Fetches the first number from the sequence - let say NextVal = 1 and stores it in the memory
  2. Generates next allocationSize=5 identifiers incrementing the above value by 1, that is: Id = 1, 2, 3, 4, 5
  3. Fetches the next number from the sequence - because of INCREMENT BY 1, the nextVal will be: 2
  4. Generates next allocationSize=5 identifiers incrementing the above value by 1, that is: Id = 2, 3, 4, 5, 6

As you can see, it will cause a dulicate error.


Now please consider this case:

  • @SequenceGenerator( ....allocationSize=5 ...)
  • CREATE SEQUENCE .... INCREMENT BY 5 ...

In this case Hibernate:

  1. Fetches the first number from the sequence - let say NextVal = 1 and stores it in the memory
  2. Generates next allocationSize=5 identifiers incrementing the above value by 1, that is: Id = 1, 2, 3, 4, 5
  3. Fetches the next number from the sequence - because of INCREMENT BY 5, the nextVal will be: 6
  4. Generates next allocationSize=5 identifiers incrementing the above value by 1, that is: Id = 6, 7, 8, 9, 10

In this case there is no duplicate error.


The last case has the disadvantage that if the sequence is used outside of Hibernate, then the sequence will produce gaps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!