Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add JPA annotation to superclass instance variables?

I am creating entities that are the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example:

public abstract class MyAbstractEntity {    @Column(name="PROPERTY") //This will not be inherited and is therefore useless here   protected String property;     public String getProperty() {     return this.property;   }    //setters, hashCode, equals etc. methods } 

Which I would like to inherit and only specify the child-specific stuff, like annotations:

@Entity @Table(name="MY_ENTITY_TABLE") public class MyEntity extends MyAbstractEntity {    //This will not work since this field does not override the super class field, thus the setters and getters break.   @Column(name="PROPERTY")    protected String property;  } 

Any ideas or will I have to create fields, getters and setters in the child classes?

Thanks, Kris

like image 243
Kristofer Avatar asked May 21 '10 14:05

Kristofer


People also ask

Why we are using JPA annotation instead of hibernate?

You use hibernate as implementation of JPA API. You should be able to change hibernate with another implementation (like EclipseLink) without changing in the code. This is why you should only use JPA annotations.

Are JPA annotations inherited?

JPA Inheritence Annotations@MappedSuperclass - This annotation is applied to the classes that are inherited by their subclasses. The mapped superclass doesn't contain any separate table. @DiscriminatorColumn - The discriminator attribute differentiates one entity from another.

Which annotation in JPA is used to customize the mapping of a field?

@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column. You can use the name attribute to specify the name of the database column which the entity attribute map.


1 Answers

You might want to annotate MyAbstractEntity with @MappedSuperclass class so that hibernate will import the configuration of MyAbstractEntity in the child and you won't have to override the field, just use the parent's. That annotation is the signal to hibernate that it has to examine the parent class too. Otherwise it assumes it can ignore it.

like image 192
sblundy Avatar answered Sep 17 '22 13:09

sblundy