John
John

Reputation: 896

Primary Key Column Name with Spring Data JPA and Hibernate

I have the following setup with Spring Data JPA and Hibernate as the persistence provider. All of my entities inherit from a base class

@MappedSuperclass
public class BaseEntity {

  @Id  
  private id;

  @Version
  private String version;

  //more common fields
}

For example:

@Entity
public class Foo extends BaseEntity {

}

This leads to a primary key column with name "ID" to be generated on the "FOO" table. I would like to change the naming of the primary key column. It should reflect the name of class or table. So it should be "FOO_ID" instead of just "ID".

I know that I could do this statically by using @Column(name = "FOO_ID"). But that would mean I have to do this for every Entity. Is there a more dynamic way to achieve this?

Upvotes: 0

Views: 3664

Answers (3)

Scott Cook
Scott Cook

Reputation: 88

I know this is an old question, but stumbled across this looking for an answer... Eventually found this solution elsewhere:

@Entity
@AttributeOverride(name="id", column=@Column(name="FOO_ID"))
public class Foo extends BaseEntity {

}

Upvotes: 2

Neil McGuigan
Neil McGuigan

Reputation: 48287

  1. Why use inheritance then? Just do it without inheritance.

  2. You could use getters/setters to rename your fields

Ex:

class Foo {

  private Long id;

  public Long getFooId() {
    return this.id;
  }

  public void setFooId(Long fooId) {
    this.id = fooId;
  }
}

Upvotes: 0

talalUcef
talalUcef

Reputation: 124

All your subClasses will have the same ID column name because of the inheritance, you can specify a common id colum name for all subClasses in the Base entity Class

Upvotes: 0

Related Questions