前言
Android开发中我们或多或少都会接触到数据库。Android中提供了一个占用内存极小的关系型数据库-SQLite。虽然Android系统中提供了许多操作SQLite的API,但是我们还是需要手动去编写SQL语句,这经常会出现一些莫名其妙的问题(😂,不要问我为什么)。所以便出现了许多ORM(对象关系映射)框架。其中比较著名的有GreenDao、OrmLite、Litepal等。下面主要介绍一下GreenDao,我平时用的最多的也是GreenDao。
GreenDao简介
offical.png官网上的介绍,greenDAO 是一个将对象映射到 SQLite 数据库中的轻量且快速的 ORM 解决方案。(greenDAO is a light & fast ORM solution that maps objects to SQLite databases.)
GreenDao特点
- 性能最大化,可能是Android平台上最快的ORM框架
- 易于使用的API
- 最小的内存开销
- 依赖体积小
- 支持数据库加密
- 强大的社区支持
GreenDao有如此多的有点,我们还有什么理由不去使用它呢。
GreenDao配置
(1) 在build.gradle(Module:app)
中添加下面代码:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
}
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
}
(2)或者在build.gradle(Project:app)
下面添加如下代码:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
}
同时在build.gradle(Module:app)
中添加下面代码:
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
}
其他配置
在build.gradle(Module:app)
中添加:
greendao {
schemaVersion 1//数据库版本号
daoPackage 'com.com.sky.downloader.greendao'//设置DaoMaster、DaoSession、Dao包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
//targetGenDirTest:设置生成单元测试目录
//generateTests:设置自动生成单元测试用例
}
custom.png
上述配置是可选项,如果不配置,则默认生成在build下:
default.png
GreenDao的基本配置就已经完成了,下面我们编写一个实体类。
实体类User
@Entity
public class User {
@Id(autoincrement = true)
private Long id;
private String name;
private int age;
}
相关注解说明:
- 实体@Entity注解
schema:告知GreenDao当前实体属于哪个schema
active:标记一个实体处于活跃状态,活动实体有更新、删除和刷新方法
nameInDb:在数据库中使用的别名,默认使用的是实体的类名
indexes:定义索引,可以跨越多个列
createInDb:标记创建数据库表
- 基础属性注解
@Id:主键 Long 型,可以通过@Id(autoincrement = true)设置自增长
@Property:设置一个非默认关系映射所对应的列名,默认是使用字段名,例如:@Property(nameInDb = "name")
@NotNull:设置数据库表当前列不能为空
@Transient:添加此标记后不会生成数据库表的列
- 索引注解
@Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
@Unique:向数据库添加了一个唯一的约束
- 关系注解
@ToOne:定义与另一个实体(一个实体对象)的关系
@ToMany:定义与多个实体对象的关系
当我们编写好实体类并添加自己需要的注解之后,点击Make Project
或者Make Module 'app'
,就会项目的build
目录下或者自己设定的目录下看到生成的三个类文件:
- DaoMaster
- DaoSession
- UserDao
后面的数据库操作需要借助这三个类来进行,同时在我们的实体类中自动生成了各个属性的get
、set
方法。
初始化GreenDao
一般建议在Application中初始化数据库
DevOpenHelper
有两个重载方法:
- DevOpenHelper(Context context,String name)
- DevOpenHelper(Context context,String name,CursorFactory factory)
context
上下文这个不用多说,name
数据库的名字,cursorFactory
游标工厂,一般不用,传入null
或者使用两个参数的方法即可。我们对外提供一个getDaoSession()
的方法供外部使用。
增
注意:Long型id,如果传入null,则GreenDao会默认设置自增长的值。
-
insert(User entity):插入一条记录
add user.png
删
- deleteBykey(Long key) :根据主键删除一条记录。
- delete(User entity) :根据实体类删除一条记录,一般结合查询方法,查询出一条记录之后删除。
-
deleteAll(): 删除所有记录。
delete.png
改
-
update(User entity):更新一条记录
update.png
查
- loadAll():查询所有记录
- load(Long key):根据主键查询一条记录
- queryBuilder().list():返回:List<User>列表
- queryBuilder().where(UserDao.Properties.Name.eq("")).list():返回:List<User>列表
-
queryRaw(String where,String selectionArg):返回:List<User>列表
query.png
总结
至此,GreenDao的基本使用方法就这些了,后面还有一些关于数据的升级等问题,后面再具体介绍。
网友评论
存数据:
String arrayString = new Gson().toJson(yourArrayList);
取数据的时候:
Type listType = new TypeToken<ArrayList<String>>(){}.getType();
List<String> arrayList = new Gson().fromJson(stringFromDb, listType)
Error:Unable to find method 'com.android.build.gradle.api.BaseVariant.getJavaCompiler()Lorg/gradle/api/Task;'.
Possible causes for this unexpected error include:
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)
The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
Stop Gradle build processes (requires restart)
Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.