Migration from Hibernate 4 to 5

后端 未结 1 793
谎友^
谎友^ 2021-01-12 15:39

I try to migrate to Spring Boot 1.4 that uses Hibernate 5. I have some backup script of a MariaDB database that includes table creation.

Due to spring-data-jpa in Sp

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 16:08

    The issue you face is that in Hibernate 4 and prior, using GenerationType.AUTO implied that if the database you're connected to supported IDENTITY or AUTO_INCREMENT data types, those would be preferred over using table-based sequences.

    With Hibernate 5, GenerationType.AUTO will default to using table-based sequences for databases that previously would have used IDENTITY or AUTO_INCREMENT. The reason for the logic change is a bit complex, but suffice to say there are better alternatives.

    My suggestion would be a multi-step migration path because this is going to be tedious depending on the size and number of tables and relationships between your entities.

    1. First, don't use the new identifier mapping generators (e.g. use false).
    2. Verify everything works, aka status-quo.
    3. Change all your @GeneratedValue annotations to use GenerationType.IDENTITY.
    4. Change to use identifier mapping generators (e.g. use true).
    5. Verify everything works, aka status-quo.

    At this point, you haven't had to change anything in your database, its stayed preciously as it was from the backup. All you've done is migrated the java code so that for new entities, you can use the new identifier mappings and preserve the old way for existing entities.

    From this point forward, I would suggest migrating one entity at a time.

    1. Change the java class to use a named sequence generator backed by the hibernate_sequences table.
    2. Determine the MAX(ID) of your entity's data and set the appropriate next id value in the hibernate_sequences table for that entity's named identifier.
    3. The tedious part here is you'll need to drop all your foreign keys related to this entity's existing ID column, alter its data type so that it isn't AUTO_INCREMENT or IDENTITY but instead most likely something like BIGINT or INT. Then you want to put the foreign key constraints back.

    At this point, that entity should begin using the sequence table's logic rather than the native AUTO_INCREMENT or IDENTITY functionality that AUTO used prior to Hibernate 5.

    For large, complex systems, this won't be fun.

    I had to evaluate whether we adapted to the new identifier things in ORM5 for a past project and we determined the time involved to adapt a complex, existing schema wasn't worth it. We ended up doing the first 1-5 steps to remain status-quo and then allowed new entities to leverage the new stuff. The plan was for developers go back and finish the last 1-3 steps on an as-needed basis over time.

    0 讨论(0)
提交回复
热议问题