EasyDBO 作為輕量級 ORM 框架,後期版本引入 Java 註解(Annotation)配置物件關聯映射,極大簡化了 XML 配置。本文解析 @Table、@TableField 核心註解原始碼,示範主鍵、生成器自訂配置,並說明關聯映射擴展。
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String tableName(); // 資料表名稱
String keyField() default "cid"; // 主鍵欄位,預設 cid
String keyGenerator() default "com.easyjf.dbo.RandomIdGenerator"; // 主鍵生成器
}
三個屬性均為字串,keyField、keyGenerator 提供預設值,採用「慣例優於配置」原則。
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
String name(); // 資料庫欄位名
boolean lazy() default false; // 延遲載入
boolean unique() default false; // 唯一約束
}
僅 name() 為必填,其餘有預設值,簡化常見情況。
@Table(tableName = "message")
public class Message implements Serializable {
@TableField(name = "cid") private String cid;
@TableField(name = "title") private String title1;
@TableField(name = "content") private String content1;
// ... getter/setter 省略
}
@Table(
tableName = "message",
keyField = "id",
keyGenerator = "com.easyjf.dbo.NullIdGenerator"
)
public class Message implements Serializable {
@TableField(name = "id") private String id;
// ... 其他欄位
}
若主鍵非 cid 或需特定生成策略(如 UUID、資料庫自增),必須顯式指定。
除基本欄位,EasyDBO 尚提供 @OneToOne、@ManyToOne、@ManyToMany 等關聯註解,支援延遲載入、級聯操作等進階功能,詳細用法請參考官方開發指南:
https://www.easyjf.com/easydbo/devguide.htm
EasyDBO 註解配置以「預設值減少樣板碼、運行時反射解析」為核心,適合中小型專案快速開發。正式版將持續完善註解屬性,建議關注版本更新。