Can I name my constraints with JPA?

HDave picture HDave · Jul 2, 2010 · Viewed 11.1k times · Source

When I use the maven-hibernate3-plugin (aka hbm2ddl) to generate my database schema, it creates many database constraints with terrifically hard-to-remember constraint names like FK7770538AEE7BC70 .

Is there any way to provide a more useful name such as FOO_FK_BAR_ID ?

If so, it would make it a tad easier to track down issues in the log files and other places where the violation doesn't tell you anything other than the constraint name.

Answer

Piohen picture Piohen · Nov 18, 2014

As of JPA 2.1 it is possible to give a name to foreign key. E.g.

@ManyToOne
@JoinColumn(foreignKey=@ForeignKey(name="MY_FANCY_FK_NAME"))
Account account;

Just make sure it is used within @JoinColumn. JavaDoc: https://docs.oracle.com/javaee/7/api/javax/persistence/ForeignKey.html#name%28%29