引言 在項目中,為了使用GreenDAO的自動生成DAO class的功能,我們必須建立entity,該entity通過java註解標識。 Schema是資料庫對象集合,我們可以通過gradle插件配置GreenDAO,除此之外,我們至少需要配置Schema的版本: 我們不僅可以配置schemaVe ...
引言
在項目中,為了使用GreenDAO的自動生成DAO class的功能,我們必須建立entity,該entity通過java註解標識。
Schema是資料庫對象集合,我們可以通過gradle插件配置GreenDAO,除此之外,我們至少需要配置Schema的版本:
// In the build.gradle file of your app project:
android {
...
}
greendao {
schemaVersion 2
}
我們不僅可以配置schemaVersion,還可以配置其他的屬性:
daoPackage:DAOs、DAOMaster和DAOSession生成的目錄,預設是entity所在的目錄
targetGenDir:預設在build/generated/source/greendao
其他......(貌似不重要)
@Entity
在Android項目中,GreenDAO通過註解表徵entity:
public class User { @Id private Long id; private String name; @Transient private int tempUsageCount; // not persisted // getters and setters for id and user ... }
我們通過@Entity對User進行註解,GreenDAO通過識別@Entity在編譯期生成支持資料庫的對象。
@Entity還支持一些屬性,對該對象進行描述,此時我們對上述代碼進行擴展:
@Entity( // If you have more than one schema, you can tell greenDAO // to which schema an entity belongs (pick any string as a name). schema = "myschema", // Flag to make an entity "active": Active entities have update, // delete, and refresh methods. active = true, // Specifies the name of the table in the database. // By default, the name is based on the entities class name. nameInDb = "AWESOME_USERS", // Define indexes spanning multiple columns here. indexes = { @Index(value = "name DESC", unique = true) }, // Flag if the DAO should create the database table (default is true). // Set this to false, if you have multiple entities mapping to one table, // or the table creation is done outside of greenDAO. createInDb = false, // Whether an all properties constructor should be generated. // A no-args constructor is always required. generateConstructors = true, // Whether getters and setters for properties should be generated if missing. generateGettersSetters = true ) public class User { ... }
基本屬性
@Entity public class User { @Id(autoincrement = true) private Long id; @Property(nameInDb = "USERNAME") private String name; @NotNull private int repos; @Transient private int tempUsageCount; ... }
@Id:對於資料庫來說,在數據表中作為主鍵,類型預設為long型,autoincrement =true使得id自增。
@Property :將java class中的欄位名映射為Property 提供的名字,在上述代碼中就是將name映射為USERNAME,預設情況下,如果欄位是駝峰命名轉為下劃線命名,如customName 轉換為 CUSTOM_NAME。
@NotNull: 標記基本類型為非空。
@Transient :表示java class中的該欄位不會存儲在資料庫中,是一個緩存值。
索引
如果我們不喜歡,GreenDAO定製的預設索引,我們可以自行設置新的索引,這是需要屬性@index。
@Entity public class User { @Id private Long id; @Index(unique = true) private String name; }
id是資料庫的唯一索引,即主鍵。但我們可以通過unique = true,指定name索引也是唯一的。