相關文件 下載本手冊
PDF (美式信紙) - 3.6Mb
PDF (A4) - 3.6Mb


4.2.2.3 註解

在 ClusterJ (如同在 JPA 中),註解是用來描述介面如何對應到資料庫中的資料表。一個帶有註解的介面如下所示

@PersistenceCapable(table="employee")
@Index(name="idx_uhash")
public interface Employee {

    @PrimaryKey
    int getId();
    void setId(int id);

    String getFirst();
    void setFirst(String first);
    String getLast();
    void setLast(String last);
  
    @Column(name="municipality")  
    @Index(name="idx_municipality")
    String getCity();
    void setCity(String city);
  
    Date getStarted();
    void setStarted(Date date);
  
    Date getEnded();
    void setEnded(Date date);

    Integer getDepartment();
    void setDepartment(Integer department);
}

此介面對應七個資料行:idfirstlastmunicipalitystartedendeddepartment。註解 @PersistenceCapable(table="employee") 用來讓 ClusterJ 知道要將 Employee 對應到哪個資料庫資料表 (在此案例中為 employee 資料表)。使用 @Column 註解是因為 getCity()setCity() 方法所暗示的 city 屬性名稱,與對應的資料行名稱 municipality 不同。註解 @PrimaryKey@Index 會告知 ClusterJ 資料庫資料表中的索引。

此介面的實作會由 ClusterJ 在執行階段動態建立。當呼叫 newInstance() 方法時,ClusterJ 會為 Employee 介面建立實作類別;此類別會將值儲存在內部的物件陣列中。

ClusterJ 並不要求每個屬性都要有註解。ClusterJ 會自動偵測資料表的主鍵;雖然在 ClusterJ 中有註解可允許使用者描述資料表的主鍵 (請參閱先前的範例),但指定時目前會忽略它。(此註解的預期用途是從網域物件模型介面產生結構描述,但目前尚不支援。)

註解本身必須從 ClusterJ API 匯入。它們可以在套件 com.mysql.clusterj.annotation 中找到,並可如此匯入

import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;