GreenDao

GreenDao配置依赖

工程配置:添加插件 更好支持GreenDao

buildscript {
    repositories {
    jcenter()
    mavenCentral() // 添加的代码
     }
    dependencies {
     classpath 'com.android.tools.build:gradle:2.3.3'
    classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
            }
}

项目配置:添加插件

apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

项目配置:添加依赖

dependencies {
//greendao
implementation 'org.greenrobot:greendao:3.2.2' // add library
}

初始化GreenDao配置

greendao{
    schemaVersion 1 //数据库版本号
    daoPackage 'com.example.lizhengjun.dao'  //数据库全路径
    targetGenDir 'src/main/java'  //存放位置
 }
    
schemaVersion--> 指定数据库schema版本号,迁移等操作会用到;
daoPackage --> dao的包名,包名默认是entity所在的包;
targetGenDir --> 生成数据库
  1. 配置文件中的设置
  2. 设置Green中的DaoMaster/DaoSession/实体类Dao生成路径
  3. 设置实体类
    @Entity
    public class Student {
    
        @Id(autoincrement = true)
        private Long id;
    
        @Property
        @NotNull
        private String name;
    
        @Property
        private int age;
    }
  1. 文件生成:Build - > ReBuild Project

  2. 在Application类中完成内容配置(或者使用工具类)
    Application有自己的生命周期,OnCreate方法必须首先被调用
    ①本类对象的获取
    ②DaoMaster、DaoSession对象的获取
    ③提供方法,获取DaoSession对象
    创建一个类 继承Application
    (注意:这里继承Application 需在清单文件中注册(不然会报空指针异常))

  1. 获取实体类Dao对象
    XXXDao xxxdao = App.getInstance().getDaoSession().getXXXDao();
    xxxdao.增删改查();
    出处。

GreenDao判断数据库中是否存在

private boolean isHased(CollectionDbBean collectionDbBean) {
        List<CollectionDbBean> list = collectionDbBeanDao.queryBuilder()
                .where(CollectionDbBeanDao.Properties.Title.eq(collectionDbBean.getTitle())).list();
        if (list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

懒加载

    //如果用户可见加载数据,不可见清空
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initData();
        } else {
            if (datas != null && datas.size() > 0) {
                datas.clear();
            }
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容