天天看點

Litepal使用心得之建立資料之間的聯系Litepal使用心得之建立資料之間的聯系

Litepal使用心得之建立資料之間的聯系

去年開始接觸到郭神的“兒子”,關于資料庫的架構——Litepal。從一個什麼都不懂得菜鳥,到用這個架構完成一些想要的功能。為郭神的創造點贊。友善自己之餘,将一些用法心得分享給大家,免得大家走彎路。

1.建立表和表之間的關系。

參考郭神的系列教程Android資料庫高手秘籍

我們也以New為例,建立對象。來說明表與表之間建立的聯系。

以新聞和評論為例,建立表與表的關聯。

public class News  extends DataSupport
{
        private int id;
        private List<Comments> comments;

    public int getId() 
    {
        return id;
    }

    public void setId(int id) 
    {
        this.id = id;
    }

//編譯器自動生成的屬性函數
    public List<Comments> getComments() 
    {
        return comments;
    }

 //編者自己加的的屬性函數,在“動态建立表與表的聯系中”要用到。與上面函數僅僅是函數名不同
 public List<Comments> getCommentsList() 

    {
        return comments;
    }

    public void setComments(List<Comments> comments) 
    {
        this.comments = comments;
    }
}
           

注意,這裡,在給News類添加了一個 int id 屬性。無須給它指派,隻需要調用news.getId( ) 便可以得到news 在資料庫中的id。在AndroidStudio中,按Alt+insert 鍵,自動生成get和set系列成員函數。這一點很重要!!!不然在後面建立表間聯系時,按照郭神的方法,無法建立聯系。

OK,繼續把Comments類建立好。

public class Comments extends DataSupport{
    private int id;
    private String content;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
           

參考郭神系列教程可知,Comments與News兩表已經建立了聯系。在資料庫中,comments表中多了一個news_id屬性。

動态添加表與表之間地關聯關系

這裡建立一個Comments類的執行個體,并且給這個執行個體與一個已存在的news綁定(假設資料庫中有很多條news,這裡從中取出第一條news).

郭神的教程是這樣的:

Comments comments=new Comments();
comments.setContent("這是一條評論");
comments.save();//必須存入資料庫中,才可以和news表建立聯系

News news=DataSupport.findFirst(News.class);//從資料庫中取出第一條資料。

news.getComments().add(comments);//建立comments與news的聯系
news.save();//儲存
           

通過實踐可以保證,comments與news确實建立了聯系。在comments的鍵值news_id中的值為剛才那條news的id。

但是!如果改成下面的代碼。則無法建立關聯。

Comments comments=new Comments();
comments.setContent("這是一條評論");
comments.save();//必須存入資料庫中,才可以和news表建立聯系

News news=DataSupport.findFirst(News.class);//從資料庫中取出第一條資料。

//這裡用自定義的屬性函數getCommentsList()來建立表與表的聯系
news.getCommentsList().add(comments);//建立comments與news的聯系
news.save();//儲存
           
但是最後在資料庫中,始終無法建立聯系。但是用*news.getComments().add(comments)*,便可以建立聯系。
           

總結

在LitePal中,建立表與表的聯系非常簡單。但是一定要注意類的屬性函數,不要自己命名,而是要利用編譯器的自動生成屬性的功能。來生成get和set系類函數。因為系統是根據成員的成員名來生成get和set方法。在LitePal的内部,很有可能是根據get()函數的函數名來确定表名,進而建立表與表之間的聯系。