所有实体都必须具有主键

在 OpenJPA 中,可在没有主键的情况下定义实体类,在该情况下将生成名为 ID 的缺省主键。EclipseLink 需要所有实体类都具有使用 @Id@EmbeddedId@IdClass 注释标识为主键的属性。

该规则扫描实体类,并验证它们是否具有通过 @Id@EmbeddedId@IdClass 注释的属性。对于没有这些已注释属性的类,为该实体添加使用 OpenJPA 生成的列的 ID 属性。 该规则限制为验证一个类中包含的实体。如果实体类扩展其他实体类或映射的超类,该规则不会标记缺少的主键。在这些情况下,如果收到类似于以下示例的运行时异常,那么您缺少主键。

Exception Description: Entity class [class org.apache.openjpa.persistence.annotations.EntityA] 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.

在以下实体类中,Entity 注释由规则标记。

import javax.persistence.Entity;

@Entity
public class EntityNoId {

}

要识别主键,请添加已注释的属性。

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.TableGenerator;

@Entity
public class EntityNoId {

    @Id
    @TableGenerator(name = "OPENJPA_SEQUENCE_TABLE", table = "OPENJPA_SEQUENCE_TABLE", pkColumnName = "ID", valueColumnName = "SEQUENCE_VALUE", pkColumnValue = "0")
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "OPENJPA_SEQUENCE_TABLE")
    private int id;
}

有关 OpenJPA 到 EclipseLink 迁移问题的信息,请参阅 OpenJPA to EclipseLink JPA Migration: Mappings 指南。