Hibernate with Oracle sequence doesn't use it

前端 未结 3 1149
时光说笑
时光说笑 2020-12-05 02:57

I have configured hibernate to use oracle sequence. Sequence is created with cache=20, increment=1.

All works fine, hibernate persisting entities. The id value is st

3条回答
  •  渐次进展
    2020-12-05 03:50

    I take it that your question is that the values of the ID column in the database are not a natural sequence, but why you are seeing gaps:

    A bit of background:

    • Every time you call select HIBERNATE_SEQUENCE.nextval from DUAL the value of the sequence is increased.
    • As your sequence name is generic rather than specific to the table, if you've got multiple entities which all use the HIBERNATE_SEQUENCE as id generator, then the values from the sequences are used in all entities.
    • If some other application uses HIBERNATE_SEQUENCE, then the value is skipped as well.
    • As you are using CACHE=20, Oracle will grab sequence numbers in blocks of 20 and then use an internal cache to return the numbers. This can lead to numbers being skipped if the cache is lost (e.g. if the DB is shut down).
    • If rows are deleted from your database, the sequence value does not change

    For example, consider the following scenario:

    You've got two entities Entity1 and Entity2 using HIBERNATE_SEQUENCE as the ID generator:

    1. Current HIBERNATE_SEQUENCE value is 100
    2. An Entity1 is inserted (uses HIBERNATE_SEQUENCE which returns 101)
    3. An Entity2 is inserted (uses HIBERNATE_SEQUENCE which returns 102)
    4. An Entity2 is inserted (uses HIBERNATE_SEQUENCE which returns 103)
    5. The Entity2 with ID 103 is deleted
    6. You manually execute select HIBERNATE_SEQUENCE.nextval from DUAL (returns 104)
    7. An Entity1 is inserted (uses HIBERNATE_SEQUENCE which returns 105)
    8. An Entity2 is inserted (uses HIBERNATE_SEQUENCE which returns 106)

    So at the end of it you'll have:

    • Entity1 with IDs (101, 105)
    • Entity2 with IDs (102, 106)

    which explains the gaps.

    EDIT:

    Even if the @SequenceGenerator were setup to use the SequenceGenerator rather than the SequenceHiLoGenerator (as pointed out by JB Nizet, which I think is a better explanation for the gaps), gaps in IDs generated by sequences are a common occurrence.

提交回复
热议问题