Android 数据库之GreenDao

1.配置gradle
Add the following Gradle configuration to your Android project:
// In your root build.gradle file:
buildscript {
    repositories {
        jcenter()
        mavenCentral() // add repository
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    }
}


 
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

 android {
}
greendao {
    schemaVersion 1                                   //版本号,升级时可配置
    daoPackage 'com.demo.greendao'             //包名
    targetGenDir 'src/main/java'                      //生成目录
}
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' // add library
}

2.创建表
@Entity(nameInDb = "student")  //表名
public class Student {
    @Id(autoincrement = true)
    private Long _id;
    private String name;
    private int age;
}
}

3.会在 com.demo.greendao我们指定的包名下自动生成
DaoMaster、DaoSession、StudentDao
4.创建DbHelper,对数据库进行操作。
public class DbHelper  {
    private static final String TAG = "DbHelper";
    private static final String DBNAME = "test.db";
    private static DaoMaster sDaoMaster;
    private static DaoSession sDaoSession;
    private Context mContext;
    private static DbHelper mInstance;

    public DbHelper(Context context) {
        mContext = context;
    }



    public DaoSession getDaoSession() {
        if (sDaoSession == null) {
            if (sDaoMaster == null) {
                sDaoMaster = getDaoMaster();
            }
            sDaoSession = sDaoMaster.newSession();
        }
        return sDaoSession;
    }

    private DaoMaster getDaoMaster() {
        if (sDaoMaster == null) {
            DaoMaster.DevOpenHelper helper = new Helper(mContext, DBNAME);
            sDaoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return sDaoMaster;
    }

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


5.对数据库进行操作

   StudentDao  studentDao = DbHelper.getInstance(this).getDaoSession().getStudentDao();
 studentDao.queryBuilder().build().list();//查询



猜你喜欢

转载自blog.csdn.net/weixin_37292229/article/details/79096381