所有實體都必須有主要索引鍵

在 OpenJPA 中,可定義不含主要索引鍵的實體類別,在此情況下,會產生一個稱為 ID 的預設主要索引鍵。 EclipseLink 需要所有實體類別都有一個屬性是利用 @Id@EmbeddedId@IdClass 註釋而識別為主要索引鍵。

此規則掃描實體類別,並驗證它們有一個透過 @Id@EmbeddedId@IdClass 標註的屬性。 對於不含這些已標註屬性的類別,請新增一個 ID 屬性,它針對此實體使用 OpenJPA 產生的直欄。 此規則限於驗證包含在一個類別中的實體。 如果該實體類別延伸其他實體類別或對映的超類別,則此規則不標示遺漏的主要索引鍵。 在這些情況下,如果您發生執行時期異常狀況(如下例),則您遺漏主要索引鍵:

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 至 EclipseLink JPA 移轉:對映手冊。