Android 本地数据库有很多,Sqlite、Dbutils、LitePa、GreenDao等,
greenDAO是一款开源的面向 Android 的轻便、快捷的 ORM 框架,将 Java 对象映射到SQLite数据库中,我们操作数据库的时候,不再需要编写复杂的 SQL语句, 在性能方面,greenDAO针对 Android 进行了高度优化, 最小的内存开销 、依赖体积小 同时还是支持数据库加密。
下面简单介绍下GreenDao的基本使用:
1、引入greenDAO
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
.......
}
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
......
//apply plugin: 'McImage'
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "..."
minSdkVersion 18
targetSdkVersion 25
versionCode 76
versionName "1.7.6"
}
//greendao配置
greendao {
//数据库版本号,升级时修改
schemaVersion 6
//生成的DAO,DaoMaster和DaoSession的包路径。默认与表实体所在的包路径相同
//daoPackage 'com.dev.base.model.db'
//生成源文件的路径。默认源文件目录是在build目录中的(build/generated/source/greendao)
//targetGenDir 'src/main/java'
}
}
apply from: 'tinkerpatch.gradle'
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:cardview-v7:26.1.0'
...
//这里直接使用了此引入,是为了后面对greenDao的数据库升级时候避免清除数据库中数据
implementation 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v1.4.0'
...
}
2、创建实体类
@Entity
public class UserBean {
@Id(autoincrement = true)
private Long id;
private String username;
private String password;
//数据库不能直接存储类,需要通过此方法转换为字符串
@Convert(converter = DepartmentBeanConverent.class, columnType = String.class)
private DepartmentBean dept; //所在部门属性
......
}
public class DepartmentBean {
//所在部门属性
private String id;
private String deptId;
private String deptName;
....
}
//通过此方法实现 实体类和字符串互相转换,在greenDao存和取数据时会帮你自动转换好
public class DepartmentBeanConverent implements PropertyConverter<DepartmentBean,String> {
private final Gson mGson;
public DepartmentBeanConverent() {
mGson = new Gson();
}
@Override
public CompanyPersonSignBean convertToEntityProperty(String databaseValue) {
// Type type = new TypeToken<List<CheckManBean>>() {
// }.getType();
DepartmentBean _cljcList = mGson.fromJson(databaseValue, DepartmentBean.class);
return _cljcList;
}
@Override
public String convertToDatabaseValue(DepartmentBean entityProperty) {
String dbString = mGson.toJson(entityProperty);
return dbString;
}
}
对注解的解释:
@Id:对象的Id,使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值
@Entity:告诉GreenDao该对象为实体,只有被@Entity注释的类才能被dao类操作
@Property:表示该属性将作为表的一个字段
@Transient:表示该属性不会被存入数据库的字段中
@Unique:表示该属性值在数据库中是唯一值
@NotNull:表示该属性不能为空
@Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改
3、数据库的初始化
private DaoSession mDaoSession_user;
public static final int CURRENT_DATABASE_CODE = 15;//数据库版本
private void initDataBase() {
//数据库和用户的UserId关联,实现权限的处理,不同用户登录请求不同数据库
String userId = SPUtils.init().getString(SPUtils.USER_ID);
MySQLiteOpenHelper helper0 = new MySQLiteOpenHelper(this, Config.DB_NAME + userId, null);
mDaoSession_user = new DaoMaster(helper0.getWritableDb()).newSession();
/*下面是数据库升级代码,后面会介绍**/
int oldDataBaseCodeUserId = SPUtils.init().getInt(SPUtils.OLD_DATABASE_VERSION_USER_ID+userId, CURRENT_DATABASE_CODE);
//数据库升级
helper0.onUpgrade(helper0.getWritableDb(), oldDataBaseCodeUserId, CURRENT_DATABASE_CODE);
SPUtils.init().putInt(SPUtils.OLD_DATABASE_VERSION_USER_ID+userId, CURRENT_DATABASE_CODE);
...
}
4、基本操作方法
- 添加数据
public void insertUser() {
userEntityDao.insert(userEntity);
userEntityDao.insertOrReplace(userEntity);//添加数据,如果有重复则覆盖
userEntityDao.insertInTx(userEntityList);
userEntityDao.insertOrReplaceInTx(userEntityList);
}
- 删除数据
public void deleteUser() {
userEntityDao.delete(userEntity);//删除指定单个
userEntityDao.deleteByKey(id);//删除指定单个
userEntityDao.deleteInTx(userEntityList);//删除指定list
userEntityDao.deleteByKeyInTx(userEntityList);//删除指定list
userEntityDao.deleteAll();//删除所有
}
- 更新数据
public void updateUser() {
userEntityDao.update(userEntity);
userEntityDao.updateInTx(userEntityList);
}
- 查询数据
public void queryUser() { userEntity = userEntityDao.queryBuilder().where(UserEntityDao.Properties.Username.eq("老板")).build().unique(); userEntity = userEntityDao.load(id); userEntity = userEntityDao.loadByRowId(id); userEntityList = userEntityDao.queryBuilder().list(); userEntityList = userEntityDao.loadAll(); }
根据条件查询:
-
“whereOr” where语句里面写的条件都是用“且”连接,whereOr里的语句使用“或”连接
“distinct” 直接过滤掉重负字段
“limit” 分页n个一页,一般和offset结合使用
“offset” 忽略查询出的前n条结果
“orderAsc” 以字段升序排序
“orderDesc”以字段降序
“preferLocalizedStringOrder” 本地化字符串排序
“orderCustom” 自定义排序 里面需要传两个参数: 一个属性 和对应的排序方案 ASC 或是 DESC
“orderRaw” 也是自定义排序, 把字段和 排序方案 写在一个字符串传入
“stringOrderCollation” 也是自定义排序 可以合并多个升降排序方案 以日期升序 且 价格降序
“notEq” 和eq相反,别傻傻在再去外面敲“!”取反
“notIn” 同上
“or” 或者
“like” 就是sql语句的LIKE"%"+string+"%"
“between” 也就是BETWEEN ? AND ? 可以取两个值的区间 (但是这条语句要慎用,不同的数据库不一样,有的是A<条件
“gt” 相当于 >
“ge”相当于 >=
“lt” 相当于 <
“le”相当于 <=
“isNull” 为空
“notIsNull” 不为空
参考:
GreenDao的基本使用:GreenDao 使用详解(入门篇)_bencheng06的博客-CSDN博客_greendao使用详解
GreenDao的基本使用:https://www.jianshu.com/p/fab571e35c02
下面简单介绍下GreenDao的使用技巧:
GreenDao直接执行sql:GreenDao直接执行sql_jifenglie的博客-CSDN博客
GreenDao根据条件删除数据:GreenDao根据条件删除数据_jifenglie的博客-CSDN博客_greendao 删除数据
GreenDao清除缓存:GreenDao清除缓存_jifenglie的博客-CSDN博客
GreenDao数据增量更新:GreenDao数据增量更新_jifenglie的博客-CSDN博客
GreenDao数据库升级不清除数据:GreenDao数据库升级不清除数据_jifenglie的博客-CSDN博客
android-database-sqlcipher Github数据库加密
GreenDaoUpgradeHelper Github数据库升级辅助