具有抽象类继承的JPA实体

Dob*_*bbo 5 ejb java-ee jboss7.x

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

public abstract class AbstractEntity {

    ...
    private long lastModified;
    ...

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

    public void setLastModified(long ts) {
       lastModified = ts;
    }
}
Run Code Online (Sandbox Code Playgroud)

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试将@Entity添加到AbstractEntity,但在部署时导致异常.

org.hibernate.AnnotationException: No identifier specified for entity:
AbstractEntity
Run Code Online (Sandbox Code Playgroud)

kos*_*tja 12

你有几种可能性.

您没有为超类定义映射.如果它应该是一个可查询的类型,你应该用它进行注释@Entity,你还需要一个@Id属性(这个缺失的@Id属性是你添加@Entity注释后得到的错误的原因 )

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

如果您根本没有注释您的超类,它将被提供程序视为瞬态,并且根本不会映射.

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

@PreUpdate
void updateModificationTimestamp() {
 lastModified = System.currentTimeMillis();
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢Kostha - "@ MappedSuperclass"注释只是我正在寻找的解决方案. (2认同)