2012-08-27 27 views
10

我正在嘗試爲一組實體創建一個基類,以減少編碼工作量和重複。我的想法是,基類有共同的元數據字段,而子類處理它們的獨特屬性。@Entity不能識別@MappedSuperclass中的@Id

我的基類:

@MappedSuperclass 
public abstract class FinanceEntityBean { 
    protected Long id; 

    @Version 
    private long version; 

    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    public Long getId() { 
     return id; 
    } 

    public void setId(final Long id) { 
     this.id = id; 
    } 
} 

第一個實體:

@Entity 
@Table(name = "tag") 
public class Tag extends FinanceEntityBean { 
} 

我已經使用這個代碼做標籤上的實體CRUD功能筆試,和他們都工作正常。

我的問題是 - 爲什麼Eclipse的(藍色)堅持認爲Tag有一個錯誤:

The entity has no primary key attribute defined

我已經改變了一個警告現在,所以我的代碼編譯,但我好奇爲什麼Eclipse不開心,如果我誤解了一些東西。

這是否爲有效的JPA 2.0代碼? Hibernate 4.1.5是我的JPA提供者。

+0

此警告/錯誤是錯誤的,您可以在首選項中將其禁用 – Kemoda

回答

8

使用混合訪問時,您必須指定訪問類型。請參閱Eclipse Dali bug 323527,以便在字段和屬性註釋時提供更好的驗證錯誤。

選項1:註釋getVersion()方法,而僅註解屬性。
選項2:指定混合接入類型如下:

@MappedSuperclass 
@Access(AccessType.PROPERTY) 
public abstract class FinanceEntityBean { 
    protected Long id; 

    @Version 
    @Access(AccessType.FIELD) 
    private long version; 

    @Id 
    @GeneratedValue(strategy=GenerationType.IDENTITY) 
    public Long getId() { 
     return id; 
    } 

    public void setId(final Long id) { 
     this.id = id; 
    } 
} 
+0

賓果!事實證明,我在版本字段上使用了字段訪問,儘管我在其他字段上使用了屬性訪問。只要我爲我的版本字段創建訪問器並將我的@Version註釋移動到getter,錯誤就消失了! – Jay

2

我相當肯定那些是有效的映射。

的JPA 2.0規範提供談到MappedSuperClasses在這個例子中(第2.11.2):

@MappedSuperclass 
public class Employee { 
    @Id protected Integer empId; 
    @Version protected Integer version; 
    @ManyToOne @JoinColumn(name="ADDR") protected Address address; 
    public Integer getEmpId() { ... } 
    public void setEmpId(Integer id) { ... } 
    public Address getAddress() { ... } 
    public void setAddress(Address addr) { ... } 
} 

// Default table is FTEMPLOYEE table 
@Entity public class FTEmployee extends Employee { 
    // Inherited empId field mapped to FTEMPLOYEE.EMPID 
    // Inherited version field mapped to FTEMPLOYEE.VERSION 
    // Inherited address field mapped to FTEMPLOYEE.ADDR fk 
    // Defaults to FTEMPLOYEE.SALARY protected Integer salary; 
    public FTEmployee() {} 
    public Integer getSalary() { ... } 
    public void setSalary(Integer salary) { ... } 
} 
7

如果FinanceEntityBean在不同的Eclipse項目從Tag定義,您可以從大理蟲"No primary key attribute in other plug-in project"患上。

解決方法是在與Tag關聯的persistence.xml文件中列出FinanceEntityBean

+1

我的錯誤是不同的,我(感謝Dali)已經在我的persistence.xml中有FinanceEntityBean,所以解決方法在我的情況下不起作用,但我很欣賞對達利錯誤的提及。 – Jay

0

我有同樣的問題,但出於不同的原因,但我沒有意識到這一點。在進一步的研究中,我發現在我的情況下,我在另一個jar中使用了MappedSuperclass。根據用戶氣https://stackoverflow.com/users/3701228/gas

「根據JPA規範,如果你有jpa類在單獨的jar你應該把它添加到persistence.xml(我不知道,如果Hibernate要求,但你可以給它嘗試添加以下條目到您的persistence.xml entity.jar「

他引用what is the right path to refer a jar file in jpa persistence.xml in a web app?作爲描述如何做到這一點。