I have an abstract class that provides some common functionality that some of the EJB entities which to inherit. One of these is a timestamp column.
public abstract class AbstractEntity {
...
private long lastModified;
...
@Column
public long getLastModified() {
return lastModified;
}
public void setLastModified(long ts) {
lastModified = ts;
}
}
and
@Table
@Entity
public class MyEntity extends AbstractEntity {
...
private Long key;
private String value;
...
@Id
public Long getKey() {
return key;
}
public void setKey(Long k) {
key = k;
}
@Column
public String getValue() {
return value;
}
public void setValue(String txt) {
value = txt;
setLastModified(System.currentTimeMillis());
}
}
The issue is that the timestamp column is not being added to the database table. Is there some annotation that needs to be added to AbstractEntity in order for the lastModified fields to be inherited as a column?
I tried adding @Entity to the AbstractEntity but that caused an exception at deployment.
org.hibernate.AnnotationException: No identifier specified for entity:
AbstractEntity
Entity classes can be both abstract and concrete.
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.
JPA Inheritence Overview Inheritence is a key feature of object-oriented programming language in which a child class can acquire the properties of its parent class. This feature enhances reusability of the code. The relational database doesn't support the mechanism of inheritance.
There are three inheritance strategies defined from the InheritanceType enum, SINGLE_TABLE , TABLE_PER_CLASS and JOINED . Single table inheritance is the default, and table per class is an optional feature of the JPA spec, so not all providers may support it.
You have several possibilities here.
You did not define a mapping for your superclass. If it is supposed to be a queryable type, you should annotate it with @Entity
and you would also need an @Id
attribute (this missing @Id
attribute is the reason for the error you are getting after adding the @Entity
annotation)
If you do not need the abstract superclass to be a queryable entity, but would like to have it's attributes as columns in tables of it's subclasses, you need to annotate it with @MappedSuperclass
If you do not annotate your superclass at all, it is considered to be transient by the provider and is not mapped at all.
EDIT: By the way, you do not have to modify the lastModified
value yourself (except you really want to) - you can let the persistence provider do it for you each time you persist the entity with a lifecycle callback:
@PreUpdate
void updateModificationTimestamp() {
lastModified = System.currentTimeMillis();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With