0

How does the seqhilo algorithm work with sequence in Hibernate with Postgresql?

    <id name="id" column="attid" type="long"
        unsaved-value="-1">
        <generator class="seqhilo">
            <param name="max_lo">1</param>
            <param name="sequence">
                att_seq
            </param>
        </generator>
    </id>

If I use this configuration and let's say current value of att_seq is 1000 then what will be the value generated by Hibernate? How does this work?

4

1 回答 1

1

Step 1: At the time of app startup hibernate initializes its internally managed lo variable to max_lo+1. So lo becomes = 2

Step 2: To generate the next value it uses the following code:

    if (maxLo < 1) {

      long val = ( (Number) super.generate(session, obj) ).longValue();

      if (val == 0) val = ( (Number) super.generate(session, obj) ).longValue();

        return IdentifierGeneratorFactory.createNumber( val, returnClass );

      }

   if ( lo>maxLo ) {

     long hival = ( (Number) super.generate(session, obj) ).longValue();

     lo = (hival == 0) ? 1 : 0;

     hi = hival * ( maxLo+1 );

     if ( log.isDebugEnabled() )

      log.debug("new hi value: " + hival);

     }

   return IdentifierGeneratorFactory.createNumber( hi + lo++, returnClass );

To conclude: First time it hits the sequence and gets the value. Multiply it by (max_lo+1) and gives you the unique id. Next time it doesn't hit the database and internally increments the last value by 1.

After that it again repeats the above cycle.

So in a way it hits the database once for every two unique ids requested

于 2013-04-11T07:04:10.853 回答