Dave
Dave

Reputation: 21924

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.

Upvotes: 30

Views: 15613

Answers (3)

Phoenix Sri
Phoenix Sri

Reputation: 1

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.

Upvotes: -2

Piohen
Piohen

Reputation: 1530

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

Upvotes: 30

Pascal Thivent
Pascal Thivent

Reputation: 570585

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.

@Entity
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.

Upvotes: 15

Related Questions