当前的 greenDAO 要求 gradle 的版本至少是 3.3!!
1.在as中导入相关的包
apply plugin: 'org.greenrobot.greendao' apply plugin: 'com.android.application' dependencies { compile 'org.greenrobot:greendao:3.2.2' }2.在build.gradle中进行配置:
buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }实体类中常用的注解:
@Entity 表明这个实体类会在数据库中生成一个与之相对应的表。
@Id 对应数据表中的 Id 字段,有了解数据库的话,是一条数据的唯一标识。
@Property(nameInDb = “STUDENTNUM”) 表名这个属性对应数据表中的 STUDENTNUM 字段。
@Property 可以自定义字段名,注意外键不能使用该属性
@NotNull 该属性值不能为空
@Transient 该属性不会被存入数据库中
@Unique 表名该属性在数据库中只能有唯一值
1.初始化
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "student.db", null); DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb()); DaoSession daoSession = daoMaster.newSession();增
StudentMsgBeanDao msgBeanDao = daoSession.getStudentMsgBeanDao(); StudentMsgBean studentMsgBean = new StudentMsgBean(); studentMsgBean.setName("zone"); studentMsgBean.setStudentNum("123456"); msgBeanDao.insert(studentMsgBean);删除
List<StudentMsgBean> list2 = msgBeanDao.queryBuilder() .build().list(); for (int i = 0; i < list2.size(); i++) { String name = list2.get(i).getName(); if (name.equals("zone")) { msgBeanDao.deleteByKey(list2.get(i).getId());//通过 Id 来删除数据 /*msgBeanDao.delete(list2.get(i));//通过传入实体类的实例来删除数据*/ } }改
List<StudentMsgBean> list3 = msgBeanDao.queryBuilder() /*.offset(1)//偏移量,相当于 SQL 语句中的 skip .limit(3)//只获取结果集的前 3 个数据 .orderAsc(StudentMsgBeanDao.Properties.StudentNum)//通过 StudentNum 这个属性进行正序排序 .where(StudentMsgBeanDao.Properties.Name.eq("zone"))//数据筛选,只获取 Name = "zone" 的数据。*/ .build() .list(); for (int i = 0; i < list3.size(); i++) { list3.get(i).setStudentNum("zone==========>"); msgBeanDao.update(list3.get(i)); }查
List<StudentMsgBean> list = msgBeanDao.queryBuilder() .offset(1)//偏移量,相当于 SQL 语句中的 skip .limit(3)//只获取结果集的前 3 个数据 .orderAsc(StudentMsgBeanDao.Properties.StudentNum)//通过 StudentNum 这个属性进行正序排序 .where(StudentMsgBeanDao.Properties.Name.eq("zone"))//数据筛选,只获取 Name = "zone" 的数据。 .build() .list();源码下载地址:https://github.com/a2978157/MygreenDAO