Customized naming of columns in JPA relationships
-
03-07-2019 - |
Question
When I make relationsships with JPA using hibernate, some terrible long and ackward column names are generated.
Eg. I have the following actionPlan_actionPlanPK
, which means that the column actionPlan
is a FK that points to actionPlanPK
.
To make it look just a little bit more neat in the DB I would like if I could give it a name myself, preferably just the name it has in the entity class that owns the relationship.
Is this possible with JPA?
Solution
Yes. It is possible to specify your own name for a column if you are not satisfied with the default names. For instance in the class with the reference to the ActionPlan you can specify:
@ManyToOne
@JoinColumn(name="actionplanId")
public ActionPlan getActionPlan(){
}
And thus, the column name will be "actionplanid".
OTHER TIPS
This capability is part of the JPA specification and allows for the naming of many of your database structures in the annotations. These include:
Naming your table as follows:
@Entity
@Table(name="better_table_name")
public class MyConvolutedClassName {
}
Naming your columns as follows:
@Column(name="better_column_name")
private Date myConvolutedDateColumn;
Naming your columns that are part of a relationship:
@ManyToOne
@JoinColumn(name="better_join_column_name")
private ClassName otherModelClass;
There's a great (though not quite up-to-date) cheatsheet for EJB 3.0 annotations (which includes JPA) available at http://www.fnogol.de/media/ejb3.0-anno-cheat-1.2.pdf.