Android GreenDao

话不多说,直接上流程

//1  根build.gradle 中导入

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

//2. 在app文件下 build.gradle下导入

apply plugin: 'org.greenrobot.greendao'
greendao {

    schemaVersion 1 //数据库版本号
    daoPackage '********************(需要填写)' //设置时生成代码的目录
    targetGenDir '*****************(需要填写)' //设置DaoMaster、DaoSession、Dao目录 }
}

 //GreenDao的依赖

implementation 'org.greenrobot:greendao:3.2.2'

--------------------------------------------------------------   以上准备工作就准备完毕了----------------------------------------------------------

接下来上代码

为了操作GreenDao更方便,我这里封装了GreenDao的单例模式(可c v)

public class DaoManager {

    private static DaoManager daoManager;
    private final DaoSession daoSession;

    public DaoManager(Context context) {
	// **为表名 
        daoSession = DaoMaster.newDevSession(context, "**.db");

    }

	//使用双重效验锁的方式单例
public static  DaoManager getIntent(Context context){
	
    if (daoManager == null){

        synchronized (DaoManager.class){

            if (daoManager == null){

                daoManager = new DaoManager(context);

            }

        }

    }

    return daoManager;
}
	//获取生成的DaoSession对象
    public DaoSession getDaoSession() {

        return daoSession;

    }
}

//省略建表

//如何调用

//在MainActivity中获取  DaoSession  和表对象

如下:

daoSession = DaoManager.getIntent(this).getDaoSession();

presonDao = daoSession.getPresonDao();

//还有一些简单的增删改查的方法

添加数据:

             presonDao.insert(new Preson(null, "lisi", "wangwu"));

查询数据:

             List<Preson> list = presonDao.queryBuilder().build().list();

修改数据:

Preson preson = presonDao.queryBuilder()
	//这是表示修改id为1的数据
        .where(PresonDao.Properties.Id.eq(1))

        .build().unique();

preson.setName("我是牛");

presonDao.update(preson);

删除数据:

//删除所有数据

presonDao.deleteAll();

 

希望能对您有所帮助

想了解更多?

                                https://blog.csdn.net/as89751

猜你喜欢

转载自blog.csdn.net/as89751/article/details/82356850
今日推荐