Search code examples
javahibernatejpaconstraintsprefix

JPA: Is there any way to add a global prefix to constraint names?


I need to add a global prefix to all of my database objects like tables and constraints, so that when I extract a DDL Schema, it'll be all nice and proper.

I know how to specify constraint names (as described here) in my Java code.

I also know how to add a global prefix to tables, as described here. It's what I have currently implemented in my project.

What I do NOT know is how to add that same global prefix to constraint names. You see, when Hibernates creates all of the database tables and constraints, it does stuff like this:

Hibernate: alter table ABC_MYTABLE1 add constraint UK_MYTABLE1_COLUMN1 unique (column1)
Hibernate: alter table ABC_MYTABLE1 add constraint UK_MYTABLE1_COLUMN2 unique (column2)
Hibernate: alter table ABC_MYTABLE2 add constraint UK_MYTABLE2_COLUMN1 unique (column1)
Hibernate: alter table ABC_MYTABLE2 add constraint UK_MYTABLE2_COLUMN2 unique (column2)
...

With 'ABC' being my global prefix. Notice how the constraint names are missing the prefix? What I essentially need is this:

Hibernate: alter table ABC_MYTABLE1 add constraint ABC_UK_MYTABLE1_COLUMN1 unique (column1)
Hibernate: alter table ABC_MYTABLE1 add constraint ABC_UK_MYTABLE1_COLUMN2 unique (column2)
Hibernate: alter table ABC_MYTABLE2 add constraint ABC_UK_MYTABLE2_COLUMN1 unique (column1)
Hibernate: alter table ABC_MYTABLE2 add constraint ABC_UK_MYTABLE2_COLUMN2 unique (column2)
...

This time both table and constraint names have the prefix.

The prefix string must be variable, I cannot hard-code it, as I need to be able to configure it in a configuration file or something like that.

My current problem is that the NamingStrategy classes do not seem to provide any way to modify constraint names whatsoever. I've googled a lot, but all I found were tickets on the official Hibernate websites, which may or may not relate to this problem. Either way, they are still open tickets.

Is there any solution to this? I do not want my schema to end up with half of my objects/constraints missing the necessary prefix.

I have to say, I find it a bit sloppy of them to provide a mechanism to change the naming strategy of tables, but miss out on constraints entirely.


Solution

  • Looks like it will be easy to do with Hibernate 5.0 (or 6?) when FK name will be in one of Naming Strategy interface (see details here).