Android數據庫框架greenDao學習筆記 2

引言

上篇博客中介紹了greenDao的集成方式,這篇博客,我們介紹如何使用greenDao創建我們需要的數據表。補一張圖(來自官網),來理解greenDao,大家意會吧。

註解

先上一張圖,來對greenDao的註解有一個直觀的認識:

Schema

通過在Gradle文件中進行配置,就無需再額外配置,它的配置選項主要有以下幾個:

  • schemaVersion:數據庫最新的版本號
  • daoPackage:生成Daos的目錄
  • targetGenDir:存儲生成代碼的路徑,一般不做配置,默認 build/generated/source/greendao
  • generateTests:是否生成單元測試代碼,值爲ture 和false,默認是ture
  • targetGenDirTests:生成測試源碼的路徑,默認 src/androidTest/java

    配置樣例:

Entity

定義實體類,常需要用到的註解

@Entity

註解 @Entity 是用來將Java Object映射成爲數據庫一張表的註解,用法如下(在數據庫中生成一張User表):

@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 支持更詳細的參數配置,如下所示:

@Entity(
        // If you have more than one schema, you can tell greenDAO
        // to which schema an entity belongs (pick any string as a name).
        //數據庫對象集合,一般不做配置,如果使用gradle配置了Schema,這裏是不生效的
        schema = "myschema",

        // Flag to make an entity "active": Active entities have update,
        // delete, and refresh methods.
        //是否激活該實體,Active的實體會自動生成更新、刪除和刷新的方法
        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.
        //是否創建數據庫表,默認是true
        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.
        //是否生成getset方法
        generateGettersSetters = true
)
public class User {
  ...
}

字段屬性(property)

@Id

選取一個Long或者long型的字段作爲實體的ID,它有一個參數 autoincrement 用來標註ID的Value是否自增長。用法示例如下:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;
}

@Property

用於定義字段的屬性,配置非默認字段名,只有一個參數 nameInDb ,用法如下:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;

    @Index(name = "index",unique = true )
    @Property(nameInDb = "NAME")
    private String name;
}

@NotNull

標註一個字段值不能爲空,示例用法如下:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;

    @Index(name = "index",unique = true )
    @Property(nameInDb = "NAME")
    @NonNull
    private String name;
}

Transient

標記一個字段不進行數據庫映射,用法示例:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;

    @Index(name = "index",unique = true )
    @Property(nameInDb = "NAME")
    @NonNull
    private String name;

    @Transient
    private String memo;
}

@Index

用於爲數據表中某一字段創建索引,有兩個參數 nameunique 需要進行配置,分表表示自定義索引名稱和強制要求所有的值唯一。示例用法如下:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;

    @Index(name = "index",unique = true )
    private String name;
}

@Unique

用於表示某一字段值唯一,同時SQLite會隱式的爲該字段創建索引,示例用法如下:

@Entity
public class Assert {

    @Id(autoincrement = true)
    private long id;

    @Index(name = "index",unique = true )
    private String name;

    @Unique
    private String memo;
}

關聯註解(Relations)

數據庫表與表之間的關係常常需要表示,1對1、1對多以及多對多的關係,這時候就需要用到關聯註解來表示,下面着重來說一下。

@ToOne

用於標註與另一實體的關聯的關係,用於標註在一個字段上去關聯對應的一個實體,示例用法如下:(表示一個訂單隻能關聯一個顧客)

@Entity
public class Order {
    @Id private Long id;

    private long customerId;

    @ToOne(joinProperty = "customerId")
    private Customer customer;
}

@Entity
public class Customer {
    @Id private Long id;
}

@ToMany

用於標註一個字段與多個實體關聯,表示1對多關係,示例用法如下(一個顧客有多個訂單):

@Entity
public class Customer {
    @Id private Long id;

    @ToMany(referencedJoinProperty = "customerId")
    @OrderBy("date ASC")
    private List<Order> orders;
}

@Entity
public class Order {
    @Id private Long id;
    private Date date;
    private long customerId;
}

@JoinEntity

用於將某個字段映射到另外一張表中,示例用法如下(產品和訂單的關係,是一種N:M的關係):

@Entity
public class Product {
    @Id private Long id;

    @ToMany
    @JoinEntity(
            entity = JoinProductsWithOrders.class,
            sourceProperty = "productId",
            targetProperty = "orderId"
    )
    private List<Order> ordersWithThisProduct;
}

@Entity
public class JoinProductsWithOrders {
    @Id private Long id;
    private Long productId;
    private Long orderId;
}

@Entity
public class Order {
    @Id private Long id;
}

樹形關係

舉例說明,如果利用註解來實現一種樹形關係,示例如下:

@Entity
public class TreeNode {
    @Id private Long id;

    private Long parentId;

    @ToOne(joinProperty = "parentId")
    private TreeNode parent;

    @ToMany(referencedJoinProperty = "parentId")
    private List<TreeNode> children;
}

雙向表

@Entity
public class Customer {
    @Id private Long id;

    @ToMany(referencedJoinProperty = "customerId")
    @OrderBy("date ASC")
    private List<Order> orders;
}

@Entity
public class Order {
    @Id private Long id;
    private Date date;
    private long customerId;

    @ToOne(joinProperty = "customerId")
    private Customer customer;
}

總結

這篇博客就講到這裏,基本涵蓋了greenDao的所有註解,以及用法,掌握了這些註解,就可以創建我們需要的數據表了,後面的關聯註解比較難,要真正掌握需要結合實際的例子來進行學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章