2016-11-07 125 views
0

這是註釋字段和註釋方法(通常爲getter)之間的區別?JPA 2.0中的JPA 2.0字段註釋與方法註釋

與現場註解實施例

@Entity 
public class MainEntity { 

    @Id 
    private Long id 

    @OneToMany 
    private RelatedEntity relatedEntity 

    //getters and setters and possible other methods 
    ... 

} 

與方法註解

@Entity 
public class MainEntity { 

    @Id 
    private Long id; 

    private RelatedEntity relatedEntity 

    //getters and setters and possible other methods 
    @OneToMany 
    public RelatedEntity getRelatedEntity(){ 
      return relatedEntity 
    } 

    //other methods etc 
    ... 

} 
+3

的區別是什麼?在一個你註釋的領域和其他方法!對於持久性來說,自JPA提供者同時支持這兩種方式沒有區別。除此之外,它完全是基於意見的 –

回答

1

使用JPA您可以使用這兩種方法在實體類中映射表中的列;字段/方法訪問不會從模式生成的角度或翻譯的查詢方面改變任何內容。一般來說,字段註釋比較乾淨(像Spring這樣的框架鼓勵它),方法註釋可以給你更多的靈活性(就像從一個抽象的實體類繼承一樣)。

請注意,在你的第二個例子中有一個錯誤:

@Entity 
public class MainEntity { 

    private Long id; 

    private RelatedEntity relatedEntity 

    //getters and setters and possible other methods 
    @Id 
    public Long getId() { 
     return id; 
    } 

    @OneToMany 
    public RelatedEntity getRelatedEntity(){ 
      return relatedEntity 
    } 

    //other methods etc 
    ... 
} 
1

從視圖用戶點實施例沒有差別,直到它是一致的,但在不同的地方使用註釋改變JPA的行爲提供者(hibernate,EclipseLink等)。

設置了註釋的位置向JPA提供商提供關於您要使用哪個access type的信息。如果你在兩個地方混合了這些設置註釋,那麼提供者會選擇一個並忽略其餘部分。例如,在第二個列表中,休眠將忽略@Id,因爲您的方法上有@OneToMany,這意味着您更願意使用AccessType.PROPERTY

當然,有時候我們不想使用屬性訪問,因爲我們有一些額外的方法提供了一些邏輯並與命名約定相匹配。那麼我們應該使用AccessType.FIELD

在項目中你應該使用一致的風格。混合風格是有效的,但是您需要爲POJO中的幾乎所有元素定義@Access