Andrea T
Andrea T

Reputation: 3107

Programmatically change default value for @Column with JPA

Given that I have a field annotated with @Column, JPA will assign the dafult name on the column in the database from the name of the filed. EG:

@Column
private String someString;

In this case the column in the DB willbe called SOMESTRING.

I would like that in case there is another annotation on the same field the rules to derive the database column name to be different. For example "_" + FIELDNAME .

EG:

@Column
@SpecialColumn
private String someString;

In this case the Column name should be : _SOMESTRING

What is the best practice to do it? Thank you!

Upvotes: 0

Views: 209

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81907

There is no way to do that with plain JPA.

At first, it looks like it should be possible with Hibernate though.

Hibernate splits the determination of column names into a two-step process.

  1. it determines the "logical" name. Which be default is whatever you provide in an @Column annotation.

  2. is converting this into a "physical" name. An actual database table column name.

So it sounds like what you are trying to do should be done in the second step, the PhysicalNamingStrategy. The problem is though, that the second step doesn't have any information where this data is coming from, so there is no easy way to determine if @SpecialColumn is present.

But I guess one could tweak the first step using a custom ImplicitNamingStrategy to encode that information in the logical name, e.g. using a suffix. Unfortunately, that neither gives you easy access to the Field, or Method where you might find your annotation. It seems to only make the AttributePath available and I'm not sure if this is sufficient for your purpose. But I think it is your only chance.

Upvotes: 2

Related Questions