数据库框架GreenDAO的简单使用

数据库框架GreenDAO的简单使用

    • 数据库框架GreenDAO的简单使用
      • 一、引入依赖(两步)
      • 二、简单使用
        • Application全局配置
        • 创建实体类
        • 运用
      • 三、拓展:做一下增删改查的静态处理使用

一、引入依赖(两步)

第一步:在Project的build.gradle下增加以下注释的属性

buildscript {
    repositories {
        mavenCentral()//add repositories because greendao needed
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'//add greendao plugin
    }
}

第二步:在你所在的Module的build.gradle下增加如下属性:

apply plugin: 'org.greenrobot.greendao'//add plugin for greendao
android {
    //配置greendao数据库相关的信息
    greendao {
        schemaVersion 1 //数据库版本号
        daoPackage 'com.example.demo_test_sqlite.greendao' //设置生成dao一系列类的包名
        targetGenDir 'src/main/java' //设置生成dao一系列类所在目录
    }
}
dependencies {
    compile 'org.greenrobot:greendao:3.2.2' //add library for greendao
    //不需要可以不依赖
    compile 'net.zetetic:android-database-sqlcipher:3.5.6'//加密库依赖
}

二、简单使用

Application全局配置

package com.example.demo_test_sqlite;

import android.app.Application;

import com.example.demo_test_sqlite.greendao.DaoMaster;
import com.example.demo_test_sqlite.greendao.DaoSession;

import org.greenrobot.greendao.database.Database;

public class NewApplication extends Application {

    private static NewApplication myApplication;

    public static NewApplication getInstance() {
        return myApplication;
    }

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

    // 是否加密
    public static final boolean ENCRYPTED = false;
    private static final String ENCRYPT_PWD = "qzx";

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        initGreenDAO();
    }

    private DaoSession daoSession;

    public DaoSession getDaoSession() {
        return daoSession;
    }

    /**
     * 初始化greendao
     */
    private void initGreenDAO() {
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, DATABASE_NAME);
        Database database = null;
        if (ENCRYPTED) {
            database = helper.getEncryptedWritableDb(ENCRYPT_PWD);
        } else {
            database = helper.getWritableDb();
//            helper.getWritableDatabase();//SQLiteDatabase
        }
        DaoMaster daoMaster = new DaoMaster(database);
        daoSession = daoMaster.newSession();
    }
}

创建实体类

【说明:id必须是Long类型否则会报错,如下这样写好后build下即可会自动生成DAO的相关类,greendao的配置已经将版本号、代码生成路径写好了】
ps:toString方法如有需要需要自己添加

以整形值作为主键

@Entity
public class SimpleTestInfo {
    @Id
    private Long id;//必须要是Long类型
    private String name;
    private int age;
    private String address;
}

不以一个整形值作为主键

@Entity
public class SimpleTest2Info {
    @Id
    private String sudentNum;
    private String name;
    private String sex;
}

运用

[注意:本示例没有考虑做异步处理,特别是在查询的时候可能会耗时间等,如果数据庞大的话正式运用需要考虑]

public class GreenDAOActivity extends AppCompatActivity {

    SimpleTestInfoDao simpleTestInfoDao;

    SimpleTest2InfoDao simpleTest2InfoDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_green_dao);

        simpleTestInfoDao = NewApplication.getInstance().getDaoSession().getSimpleTestInfoDao();

        simpleTest2InfoDao = NewApplication.getInstance().getDaoSession().getSimpleTest2InfoDao();
    }

    /**
     * 检查是否数据库中已经存在该学生数字的对象
     * */
    private boolean checkExistsByNum(String studentNum) {
        SimpleTest2Info simpleTest2Info = simpleTest2InfoDao.queryBuilder().where
                (SimpleTest2InfoDao.Properties.SudentNum.eq(studentNum)).build().unique();
        if (simpleTest2Info != null) {
            return true;
        } else {
            return false;
        }
    }

    private long count = 0;

    //数据的增删该查

    public void addData(View view) {
//        SimpleTestInfo simpleTestInfo = new SimpleTestInfo(count,"七子笑",27,"合肥");
//        simpleTestInfo.setName("七子笑");
//        simpleTestInfo.setAge(27);
//        simpleTestInfo.setAddress("合肥");
//        simpleTestInfoDao.insertOrReplace(simpleTestInfo);
//
//        count++;
    }

    public void delData(View view) {
//        simpleTestInfoDao.deleteAll();
//        count = 0;

        simpleTest2InfoDao.deleteAll();
        count = 0;
    }

    public void queryData(View view) {
//        simpleTestInfoDao.loadAll()
//        List list = simpleTestInfoDao.queryBuilder().list();
//        Iterator iterator = list.iterator();
//        while (iterator.hasNext()) {
//            Log.d("zbv", "info=" + iterator.next() + "/n");
//        }

        List list = simpleTest2InfoDao.loadAll();
        for (SimpleTest2Info simpleTest2Info : list) {
            Log.d("zbv", "imfo2=" + simpleTest2Info);
        }
    }

完毕

三、拓展:做一下增删改查的静态处理使用

package com.example.demo_test_sqlite.specialDAO;

import com.example.demo_test_sqlite.greenDaoEntities.SimpleTestInfo;
import com.example.demo_test_sqlite.greendao.SimpleTestInfoDao;

import java.util.List;

/**
 * 静态方法专供SimpleTestInfo的数据库增删改查
 */
public class SimpleTestInfoSpecialOperatioin {


    public static void insertDataToDB(SimpleTestInfoDao simpleTestInfoDao, SimpleTestInfo simpleTestInfo) {
        //如果存在就替换
        simpleTestInfoDao.insertOrReplace(simpleTestInfo);
    }

    public static void deleteAllDataFromDB(SimpleTestInfoDao simpleTestInfoDao) {
        //如果存在就替换
        simpleTestInfoDao.deleteAll();
    }

    //一般都是一句主键删除
    public static void deleteDataByOneKey(SimpleTestInfoDao simpleTestInfoDao, long id) {
        //检查是否存在
        boolean exist = checkExistsByNum(simpleTestInfoDao, id);
        if (exist) {
            simpleTestInfoDao.deleteByKey(id);
        }
    }

    private static boolean checkExistsByNum(SimpleTestInfoDao simpleTestInfoDao, long id) {
        SimpleTestInfo simpleTestInfo = simpleTestInfoDao.queryBuilder().
                where(SimpleTestInfoDao.Properties.Id.eq(id)).build().unique();
        if (simpleTestInfo != null) {
            return true;
        } else {
            return false;
        }
    }

    //例如一句名字改年龄
    public static void updateDataByName(SimpleTestInfoDao simpleTestInfoDao, String name, int age) {
        SimpleTestInfo simpleTestInfo = simpleTestInfoDao.queryBuilder().
                where(SimpleTestInfoDao.Properties.Name.eq(name)).build().unique();
        if (simpleTestInfo != null) {
            simpleTestInfo.setAge(age);
            simpleTestInfoDao.update(simpleTestInfo);
        }
    }

    public static List QueryAllDataFromDB(SimpleTestInfoDao simpleTestInfoDao) {
//        List allDatas = simpleTestInfoDao.loadAll();

        //可以一句where条件查询一部分符合条件的数据链表
        List allDatas = simpleTestInfoDao.queryBuilder().list();

        return allDatas;

    }

}

你可能感兴趣的:(Android,数据库)