简体   繁体   中英

Change Hibernate sequence generation for existing data

I recently came across this behavior of Hibernate when trying to move from identity column to sequence based id generation for our business entities. The problem is that we have been using hibernate_sequence generation on Oracle since the first deployment of our application.

So the question is: is it safe to set the following Hibernate's parameter to true on an existing production database without messing up the already generated ids?

hibernate.id.new_generator_mappings=true

EDIT: The Hibernate documentation describes that the change is not backwards compatible with existing databases.

We are using HIBERNATE_SEQUENCE.NEXTVAL in database migrations and this is clearly not at all safe to do, since the NEXTVAL might conflict with a pre-existing id.

If I am not terribly wrong, backwards compatibility could be gained by setting the HIBERNATE_SEQUENCE 's current value to the maximum id in the database. Am I correct? Is there any way to find this out?

If you want to migrate to hibernate.id.new_generator_mappings=true, you have to do two things:

  1. Set the increment by of the database sequences to the same value as the allocationSize in Hibernate. The default allocationSize is 50.
  2. After setting hibernate.id.new_generator_mappings=true Hibernate will produce values starting with SEQ.NEXTVAL-allocationSize. So you have to increment the sequence with allocation size. That means selecting a SEQ.NEXTVAL.

Here is the Oracle PL/SQL script I was running before the migration:

  DECLARE
    v NUMBER;
  BEGIN
    FOR r IN (select sequence_name from user_sequences) LOOP
      EXECUTE IMMEDIATE 'ALTER SEQUENCE '|| r.sequence_name ||' INCREMENT BY 50';
      EXECUTE IMMEDIATE 'SELECT '|| r.sequence_name ||' .NEXTVAL FROM DUAL' INTO v;
    END LOOP;
  END;
  /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM