JPA: Give a name to a Foreign Key on DB?
I have a simple questions. How can I give a name to the Foreign Key relations that arise from the @ ManyToOne开发者_开发问答 annotation ?
With JPA 2.1 you can just do this with the foreignKey annotation:
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@ManyToOne
@JoinColumn(name = "company_id", nullable = false, foreignKey = @ForeignKey(name="FK_COMPANY__ROUTE"))
private Company company;
Do not confuse with the deprecated hibernate equivalent
As of JPA 2.1 it is possible to define foreign keys via @ForeignKey annotation.
Unfortunately, it is not very useful if you only need to change the name. If you specify custom name of the FK, you also have to specify SQL definition of the FK. That is at least the way it works in EclipseLink 2.5.0.
If you are interested in naming the column used in the foreign key, one may specify the name of the column used to create the foreign key, using the @JoinColumn
annotation along with the @ManyToOne
annotation. The value of the name
attribute of the @JoinColumn
annotation is used by the JPA provider to map the column name in the table to the entity's attribute.
However, the name of the foreign key constraint created itself cannot be configured. At the time of writing this, it is not possible to specify the name of the foreign key constraint using a JPA annotation or configuration parameter in the OR mapping files. If you need to change the name of the foreign key constraint, then you must create the DDL statement yourself, instead of relying on the JPA provider to do this.
I think @ForeignKey doesn't work with @JoinTables or I don't know how to set custom names by this, I have tried it on @JoinTable->foreignKey and @JoinColumn->foreignKey
精彩评论