0
votes

I'm new to Liquibase + Hibernate.

I have a table named Users, with columns {Id, FirstName, LastName, YearOfBirth, .....}. I set with Hibernate annotation a unique constraint for the couple {Id, LastName}.

Now, I decided that I want to update the constraint, to include the FirstName column, meaning I want my unique constraint to be {Id, FirstName, LastName}. Can this be done through Liquibase, on my existing db, through a changeset?

I thought about dropping the old constraint through a changeset, and creating the new constraint with another. The problem is, I don't know the name of the old constraint, neither the names of the indexes following it. And since Liquibase/Hibernate auto-generate names for the constraints/indexes, I don't want to search through a query to fetch the specific constraint name.

I'm searching for a solution that is more generic, so I can tackle same future issues.

Any suggestions?

I'm using Java 8, Hibernate 5.2.10, Liquibase 3.5.2

2

2 Answers

0
votes

Unfortunately, the index name is a required field when dropping it. Here is the relevant documentation from liquibase.

In this case, you will need to drop the index using SQL commands. Depending on what the underlying database is, you will need to programmatically figure out the name of the index assigned to the table that you would like to drop, based on the column names of the index. For example, if you are using Oracle database you could run the SQL explained here and capture these commands in a sql file. Liquibase supports including SQL files as changesets, so you will need to use the sqlFile tag in your changeSet as explained here so that the sql statements that you captured earlier is run. Once the index is dropped, you could use the liquibase changeSet again to add a new index/constraint as needed.

0
votes

Some notes for the future:

You can set a unique constraint name by this way:

@Table(uniqueConstraints = 
    @UniqueConstraint(columnNames = { "unique_field" }, name = "UK_users_unique_field")

I think, you shouldn't create a schema by the Hibernate, if you want to use Liquibase. You need to create a schema by Liquibase with your SQL scripts. You can generate a SQL script by Hibernate of course.

Use

hibernate.hbm2ddl.auto=validate 

to validate a database schema only, without creating anything.