具有抽象类继承的JPA实体

时间:2013-01-17 12:41:09

标签: java-ee ejb jboss7.x

我有一个抽象类,它提供了一些继承的EJB实体的常用功能。其中一个是时间戳列。

public abstract class AbstractEntity {

    ...
    private long lastModified;
    ...

    @Column
    public long getLastModified() {
        return lastModified;
    }

    public void setLastModified(long ts) {
       lastModified = ts;
    }
}

@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());
    }
}

问题是时间戳列未添加到数据库表中。是否需要将一些注释添加到AbstractEntity中,以便将lastModified字段作为列继承?

我尝试将@Entity添加到AbstractEntity,但这会在部署时引发异常。

org.hibernate.AnnotationException: No identifier specified for entity:
AbstractEntity

2 个答案:

答案 0 :(得分:12)

你有几种可能性。

您没有为超类定义映射。如果它应该是可查询类型,则应使用@Entity对其进行注释,并且还需要@Id属性(此缺失的@Id属性是您获得错误的原因添加@Entity注释后)

如果您不需要将抽象超类作为可查询实体,但希望将其属性作为其子类的表中的列,则需要使用@MappedSuperclass

对其进行注释。

如果你根本没有注释你的超类,它被提供者认为是暂时的,并且根本没有映射。

编辑:顺便说一句,您不必自己修改lastModified值(除非您真的想要) - 您可以让持久性提供程序每次都为您执行此操作你使用生命周期回调来持久化实体:

@PreUpdate
void updateModificationTimestamp() {
 lastModified = System.currentTimeMillis();
}

答案 1 :(得分:0)

您必须在AbstractEntity类的上方指定@MappedSuperclass注释。 这意味着您指定在AbstractEntity类中注释的是您要扩展此类的类的一部分。

您还要注意jdbc表 - 映射的列名。

相关问题