Search code examples
hibernatejpalockingversioning

Hibernate: Adding versioning to a non versioned DB


I created a db some time ago using hibernate (JPA), however I didn't included @version fields for any entities. Turns out that this project became something important and now I need to use versioning (versioning with optimistic locking).

I know I need to add a new property (field) to every single entity with @version annotation.

Question: Does anyone know how can I update the real DB (mysql) to include version columns without data loss and too much work?

Thanks very much.


Solution

  • Create a SQL statement which create the column for the tables of all entities you want to and the @Version attribute. Then use an other query to set the value of this columns for all rows to 1.

    An little bit other way is to create the column with an default value, and then remove the default. (Works for MYSQL)

    ALTER TABLE xyz ADD version integer NOT NULL DEFAULT 1;
    ALTER TABLE xyz CHANGE version version integer NOT NULL;
    

    The purpuse of this approach is that as long as you not run the second statement (remove the default), the old application will run, even if it not set a value to the version column when it creates new objects.