java - 如何解决从另一个实体 (JPA) 继承的实体的 'no primary key specified'?

标签 java jpa eclipselink

我想要一个所有文档类型通用的父类(super class):

@Entity
public abstract class Doc implements Serializable
{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected long docId;

    public long getDocId()
    {
        return docId;
    }

    public void setDocId(long docId)
    {
        this.docId = docId;
    }

}

我想为每种文档类型创建子类:

@Entity
@Table(name = "DocTypeA")
public class DocTypeA extends Doc implements Serializable
{
    // other child fields
}

但它给出了一个错误,并说 DocTypeA 需要一个主键。如何隔离主键并将其放在父类(super class)中?因为所有子类都将具有相同的 id 字段。

我正在使用 EclipseLink。

我的另一个问题是:为什么我需要将 @Entity 放在抽象类中?作为一个抽象类,它不能被实例化,那么将它标记为一个实体有什么意义呢?真的有必要吗?我不会坚持父类(super class)。我只需要它来隔离所有子类中通用的代码。

堆栈跟踪很长,相关部分粘贴在下面:

Exception Description: Entity class [class repository.DocTypeA] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.

最佳答案

根据official JavaDoc注释 @MappedSuperclass:

Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

这就是你要找的。因此 abstract 类可以很容易地用于实体的公共(public)属性,在大多数情况下是主键或 DB 生成的对象标识符。该抽象类的注释字段将仅映射到具体子类:

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. When applied to the subclasses the inherited mappings will apply in the context of the subclass tables.

像这样交换抽象类Doc中的@Entity注解:

@MappedSuperclass
public abstract class Doc implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected long docId;
    //...
}

你应该可以开始了。

希望对您有所帮助。

关于java - 如何解决从另一个实体 (JPA) 继承的实体的 'no primary key specified'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36509398/

相关文章:

java - 为什么 Java StringReader 会抛出 IOException?

java - Spring Boot - Maven 构建错误

xml - 使用 XMLStreamReader 和 StreamFilter 根据子元素过滤出元素

java - 创建 JPA native 查询很慢

java - 在 Java 中添加再见来创建新号码

Java如何对链表进行排序?

java - unix 中忽略非 ascii csv 分隔符

Hibernate - 使用编程事务惯用语的 CMT EJB

java - 将 MySql 查询转换为 JPA 命名查询

java - Eclipselink 获取递归实体给出不完整的结果