GreenDao学习

2015/6/25 posted in  Android

准备工作

github下载工程

https://github.com/greenrobot/greenDAO

android studio导入DaoExampleGenerator

下载所需的jar包

http://search.maven.org/#search%7Cga%7C1%7CgreenDao
下载greendao-generator-1.3.0.jar 和greendao-1.3.7.jar
http://mvnrepository.com/artifact/org.freemarker/freemarker
下载freemarker-2.3.20.jar

导入jar包

在DaoExampleGenerator工程中新建lib文件夹,将jar包add as library
编译报错DaoGenerator找不到。build.gradle中 注释掉//compile project(':DaoGenerator')

生成DaoGenerator生成库

main

/*
 * Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.greenrobot.daogenerator.gentest;

import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
import de.greenrobot.daogenerator.ToMany;

/**
 * Generates entities and DAOs for the example project DaoExample.
 * 
 * Run it as a Java application (not Android).
 * 
 * @author Markus
 */
public class ExampleDaoGenerator {

    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(1000, "de.greenrobot.daoexample");

        addNote(schema);
        addCustomerOrder(schema);
        addPrice(schema);

        new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
    }

    private static void addPrice(Schema schema) {
        Entity note = schema.addEntity("Price");
        note.addIdProperty();
        note.addIntProperty("Price").notNull();
    }

    private static void addNote(Schema schema) {
        Entity note = schema.addEntity("Note");
        note.addIdProperty();
        note.addStringProperty("text").notNull();
        note.addStringProperty("comment");
        note.addDateProperty("date");
    }

    private static void addCustomerOrder(Schema schema) {
        Entity customer = schema.addEntity("Customer");
        customer.addIdProperty();
        customer.addStringProperty("name").notNull();

        Entity order = schema.addEntity("Order");
        order.setTableName("ORDERS"); // "ORDER" is a reserved keyword
        order.addIdProperty();
        Property orderDate = order.addDateProperty("date").getProperty();
        Property customerId = order.addLongProperty("customerId").notNull().getProperty();
        order.addToOne(customer, customerId);

        ToMany customerToOrders = customer.addToMany(order, customerId);
        customerToOrders.setName("orders");
        customerToOrders.orderAsc(orderDate);
    }

}

分析

Schema schema = new Schema(1000, "de.greenrobot.daoexample");

参数1:数据库版本号
参数2:生成的类的路径

路径需要先创建否则会报错

运行程序后

This program comes with ABSOLUTELY NO WARRANTY
Processing schema version 1000...
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/NoteDao.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/Note.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/CustomerDao.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/Customer.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/OrderDao.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/Order.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/PriceDao.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/Price.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/DaoMaster.java
Written /Users/xuyushi/Downloads/greenDAO-master/DaoExample/src-gen/de/greenrobot/daoexample/DaoSession.java
Processed 4 entities in 153ms

Process finished with exit code 0

发现生成了4个 类 和dao类,1个DaoMaster,1个DaoSession.

创建表

在主函数中

addPrice(schema);

函数实现

private static void addPrice(Schema schema) {
    Entity note = schema.addEntity("Price");
    note.addIdProperty();
    note.addIntProperty("Price").notNull();
}
Entity note = schema.addEntity("Price");

参数:表名

默认表名就是类名,也可以自定义表名

可以加入

dao.addIdProperty().primaryKey().autoincrement();

设置一个自增长ID列为主键

不写系统会默认生成ID为主键

note.addIntProperty("Price").notNull();

加入价格,int类型,不能为空

常用增删查改功能

  1. 新建android工程
  2. 将之前生成的de.greenrobot.daoexample复制到com.example.xuyushi.greendaotest同级目录下
  3. 将下载的DaoCore中的de.greenrobot.dao复制到com.example.xuyushi.greendaotest同级目录下
  4. 新建AppApplication 继承系统Application类,在此实现getDaoMaster、getDaoSession 代码如下
    ```java
    package com.example.xuyushi.greendaotest;

import android.app.Application;
import android.content.Context;

import de.greenrobot.daoexample.DaoMaster;
import de.greenrobot.daoexample.DaoSession;

/**
* Created by xuyushi on 15/6/29.
*/
public class AppApplication extends Application {
public static final String DATABASE_NAME = "datatest";
private static DaoMaster daoMaster;
private static DaoSession daoSession;

/**
 * 取得DaoMaster
 *
 * @param context
 * @return
 */
public static DaoMaster getDaoMaster(Context context) {
    if (daoMaster == null) {
        DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, DATABASE_NAME, null);
        daoMaster = new DaoMaster(helper.getWritableDatabase());
    }
    return daoMaster;
}

/**
 * 取得DaoSession
 *
 * @param context
 * @return
 */
public static DaoSession getDaoSession(Context context) {
    if (daoSession == null) {
        if (daoMaster == null) {
            daoMaster = getDaoMaster(context);
        }
        daoSession = daoMaster.newSession();
    }
    return daoSession;
}

}



 此时就可以在此安卓工程中使用之前生成的类了




### 新建 DBHelper类,实现数据库的功能
```java
package de.greenrobot;

import android.content.Context;

import com.example.xuyushi.greendaotest.AppApplication;

import java.util.List;

import de.greenrobot.daoexample.CustomerDao;
import de.greenrobot.daoexample.DaoSession;
import de.greenrobot.daoexample.Note;
import de.greenrobot.daoexample.NoteDao;
import de.greenrobot.daoexample.OrderDao;
import de.greenrobot.daoexample.Price;
import de.greenrobot.daoexample.PriceDao;

/**
 * Created by xuyushi on 15/6/29.
 */
public class DBHelper {
    private static Context mContext;
    private static DBHelper instance;
    private CustomerDao Customer;
    private NoteDao Note;
    private OrderDao Order;
    private PriceDao Price;


    private DBHelper() {
    }

    public static DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper();
            if (mContext == null) {
                mContext = context;
            }

            // 数据库对象
            DaoSession daoSession = AppApplication.getDaoSession(mContext);
            instance.Customer = daoSession.getCustomerDao();
            instance.Order = daoSession.getOrderDao();
            instance.Note = daoSession.getNoteDao();
            instance.Price = daoSession.getPriceDao();


        }
        return instance;
    }

    /**
     * 添加数据
     */
    public void addToNoteTable(Note note) {
        if (null == Note) {
            return;
        }
        if (null == note) {
            return;
        }
        Note.insert(note);
    }

    public List<Note> getNote() {
        return Note.loadAll();
    }

    public void addPriceTable(Price price) {
        if (null == Price) {
            return;
        }
        if (null == price) {
            return;
        }
        Price.insert(price);
    }

    public List<Price> getPrice() {
        return Price.loadAll();
    }

}

在getIstence方法中需要将表对象都实例化出来

// 数据库对象
    DaoSession daoSession = AppApplication.getDaoSession(mContext);
    instance.Customer = daoSession.getCustomerDao();
    instance.Order = daoSession.getOrderDao();
    instance.Note = daoSession.getNoteDao();
    instance.Price = daoSession.getPriceDao();
    ```
之后实现table的增删查改函数。

本文举例加入了addPriceTable和getPrice函数
### 主Activity中验证

```java
long id = 1;
price = new Price(id, 22);
//    price.setId(id);
DBHelper.getInstance(this).addPriceTable(price);
ListPrice=DBHelper.getInstance(this).getPrice();

调试可以发现Listpice的id为1 Price为22