GreenDao3.2使用笔记(一)

一、配置:
1.在build.gradle(Project)中添加依赖

 dependencies {

        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'

    }

2.在build.gradle(Module)中添加依赖

apply plugin: 'org.greenrobot.greendao'

android{
//greendao配置
    greendao {
        //版本号,升级时可配置
        schemaVersion 1
        //dao创建的目录
        daoPackage 'com.mcp1993.greendaodemo.dao'
        targetGenDir 'src/main/java'
    }
}
dependencies {
    //greendao依赖
    compile 'org.greenrobot:greendao:3.2.0'
}

二、使用
1.创建bean。

@Entity
public class Challenge_horData implements Serializable{
    private static final long serialVersionUID =1L;
    private String uniquekey;
    private String title;
    private String date;
    private String category;
    private String author_name;
    private String url;
    private String thumbnail_pic_s;
    private String thumbnail_pic_s02;
    private String thumbnail_pic_s03;

    @Generated(hash = 134817119)
    public Challenge_horData(String uniquekey, String title, String date, String category, String author_name, String url,
            String thumbnail_pic_s, String thumbnail_pic_s02, String thumbnail_pic_s03) {
        this.uniquekey = uniquekey;
        this.title = title;
        this.date = date;
        this.category = category;
        this.author_name = author_name;
        this.url = url;
        this.thumbnail_pic_s = thumbnail_pic_s;
        this.thumbnail_pic_s02 = thumbnail_pic_s02;
        this.thumbnail_pic_s03 = thumbnail_pic_s03;
    }
    @Generated(hash = 255457321)
    public Challenge_horData() {
    }
    public String getUniquekey() {
        return uniquekey;
    }

    public void setUniquekey(String uniquekey) {
        this.uniquekey = uniquekey;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getAuthor_name() {
        return author_name;
    }

    public void setAuthor_name(String author_name) {
        this.author_name = author_name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getThumbnail_pic_s() {
        return thumbnail_pic_s;
    }

    public void setThumbnail_pic_s(String thumbnail_pic_s) {
        this.thumbnail_pic_s = thumbnail_pic_s;
    }

    public String getThumbnail_pic_s02() {
        return thumbnail_pic_s02;
    }

    public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
        this.thumbnail_pic_s02 = thumbnail_pic_s02;
    }

    public String getThumbnail_pic_s03() {
        return thumbnail_pic_s03;
    }

    public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
        this.thumbnail_pic_s03 = thumbnail_pic_s03;
    }
}

然后rebuild project,就会自动生成:
![YFP2O]2O}VBCDV24)9IK$DP.png](http://upload-images.jianshu.io/upload_images/2261176-a2539a7b24340e08.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]
这里记录一下注解:
@Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作
@Id:对象的Id,必须使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值
@Property:可以自定义字段名,注意外键不能使用该属性
@NotNull:属性不能为空
@Transient:使用该注释的属性不会被存入数据库的字段中
@Unique:该属性值必须在数据库中是唯一值
@Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改

2.在Application初始化greendao数据库。

public class APP extends Application{
    public static DaoSession mDaoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        initGreenDao();//初始化greendao数据库
    }

    private void initGreenDao() {
        //DevOpenHelper每次数据库升级会清空数据,一般用于开发
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"geendao_db",null);
        Database db = helper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();
    }

    public static DaoSession getDaoSession(){
        return mDaoSession;
    }

DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现
DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表
DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API

3.在activity中使用。
加载数据

 //读缓存,判断数据库是否为空,网络状态
        if (null != APP.getDaoSession().getChallenge_horDataDao().loadAll()
                && 0 <APP.getDaoSession().getChallenge_horDataDao().loadAll().size()
                    && !NetworkUtil.isAvailable(MainActivity.this)){
            datas.clear();//清空集合,为了保险起见
            datas.addAll(APP.getDaoSession().getChallenge_horDataDao().loadAll());

            mAdapter = new HorRecyclerAdapter(datas, MainActivity.this);
            recy_clerview.setAdapter(mAdapter);
            recy_clerview.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener(){
                @Override
                public void onTouchEvent(RecyclerView rv, MotionEvent e) {
                    super.onTouchEvent(rv, e);
                }
            });
            mAdapter.setOnItemClickListener(this);
        }else {
            //加载网络数据
            loadData();
        }

数据获取成功后添加到数据库

 //将数据插入数据库,插入数据的时候用到Lambda表达式
                Observable.from(datas).subscribeOn(Schedulers.io()).subscribe(challenge_horData -> {
                         //避免插入重复数据的逻辑
                    count = APP.getDaoSession().getChallenge_horDataDao().queryBuilder().where(Challenge_horDataDao.Properties.Uniquekey.eq(challenge_horData.getUniquekey())).count();
                    if (count == 0){
                        APP.getDaoSession().getChallenge_horDataDao().insertOrReplaceInTx(challenge_horData);
                    }else {
                        //刷新操作,清除bean,插入数据
                        APP.getDaoSession().getChallenge_horDataDao().deleteAll();
                        APP.getDaoSession().getChallenge_horDataDao().insertOrReplaceInTx(challenge_horData);
                    }

                });

demo代码
an example

推荐阅读更多精彩内容