Can I name my constraints with JPA?

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.


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

Account account;

Just make sure it is used within @JoinColumn. JavaDoc:

Hibernate has a @ForeignKey annotation allowing to override the constraint name. From the reference documentation:

2.4.6. Collection related annotations


Foreign key constraints, while generated by Hibernate, have a fairly unreadable name. You can override the constraint name by use @ForeignKey. Note that this annotation has to be placed on the owning side of the relationship, inverseName referencing to the other side constraint.

public class Woman {
    @ManyToMany(cascade = {CascadeType.ALL})
    @ForeignKey(name = "TO_WOMAN_FK", inverseName = "TO_MAN_FK")
    public Set<Man> getMens() {
        return mens;

alter table Man_Woman add constraint TO_WOMAN_FK foreign key (woman_id) references Woman
alter table Man_Woman add constraint TO_MAN_FK foreign key (man_id) references Man

But I'm not aware of a standard JPA equivalent.

Normally in an enterprise stack, DBAs will not and should not allow systemic entity creation in their database. They will usually ask for the DDLs to be inserted manually and you will set your Hibernate apps ddl-auto to the update mode and not create or create-drop mode. This is a ideal scenario in most of the brands I worked with. Having said, you can let the DBA decide to rename the Constraints through the alter-table statements that Hibernate will generate for you. Also, the Primary key constraint names will also be managed by DBAs once the Create table DDL is handed over to them.

If you are in a full stack role where you decide everything, you can only change the Foreign key name with current releases using the @ForeignKey annotation.

But I would still recommend, manual insertion of DDL statements to your Database rather than allowing a systemic process to take control since maintaining the the Database and de-fragmenting the structure becomes easier if a manual DBA architecture is embraced.

Hope this answers your question.

Need Your Help

How to convert UTF16 into text using php

php utf

I have one column in DB containing UTF16 string. Right now, I want to convert the UTF16 string into normal text. How to achieve this using php?