Android GreenDao使用

  1. gradle添加依赖
```groovy
// In your root build.gradle file:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0' // add plugin
    }
}
 
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
 
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}
  1. 配置Module根目录下的build.gradle文件
android {
  ......
  // 数据库的版本及Dao相关设置
  greendao {
    // 数据库schema版本,也可以理解为数据库版本号
    schemaVersion 1000
    //  设置DaoMaster 、DaoSession、Dao包名
    daoPackage  'com.mazaiting.greendaotest.db.dao'
    //  设置DaoMaster 、DaoSession、Dao目录
    targetGenDir 'src/main/java'
    //  设置自动生成单元测试用例
    generateTests
  }
}
  1. 新建实体类
package com.mazaiting.greendaotest.db.entry;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
/**
 * Created by mazaiting on 2017/9/7.
 */
@Entity
public class NewFriend {
  // 设置自增长,不能设置为int
  @Id(autoincrement = true)
  private long id;
  private String name;
  private int age;

}
  1. 重新编译工程(build->Rebuild Project)。
    编译完成后,在com.mazaiting.greendaotest.db.dao下生成如下文件:
Android GreenDao使用_第1张图片
测试1.png
  1. 使用GreenDao添加数据
  /**
   * 使用GreenDao
   */
  private void userGreenDao() {
    DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "test.db");
    DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
    DaoSession daoSession = daoMaster.newSession();

    NewFriend newFriend = new NewFriend();
    newFriend.setName("mazaiting");
    newFriend.setAge(22);
    daoSession.insert(newFriend);
  }

运行后,在"/data/data/com.mazaiting.greendaotest/databases/"路径下生成test.db数据库,库中生成相对应的实体表名(NEW_FRIEND),并将数据插入了其中。

Android GreenDao使用_第2张图片
结果.png
  1. 工具类
package com.mazaiting.greendaotest.db.dao;

import android.content.Context;

/**
 * Created by mazaiting on 2017/9/7.
 */

public class DbManager {

  private static final String DB_NAME = "test.db";

  private static DbManager mDbManager = null;
  private static DaoSession mDaoSession = null;

  private DbManager(Context context){
    DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, DB_NAME);
    DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
    mDaoSession = daoMaster.newSession();
    // 在控制台打印出sql语句和查询的值
    QueryBuilder.LOG_SQL = true;
    QueryBuilder.LOG_VALUES = true;
  }

  public static DbManager getInstance(Context context){
    if (null == mDbManager){
      synchronized (DbManager.class){
        if (null == mDbManager){
          mDbManager = new DbManager(context);
        }
      }
    }
    return mDbManager;
  }

  public NewFriendDao getNewFriendDao(){
    return mDaoSession.getNewFriendDao();
  }
}

你可能感兴趣的:(Android GreenDao使用)