Android -- GreenDao3.2的简单使用
http://www.cnblogs.com/wjtaigwh/p/6394288.html
https://github.com/greenrobot/greendao
GreenDao是使用ORM(Object RelationShop Mapping)对象关系映射,就是通过GreenDao将数据库和Bean关联起来有以下优点:
-
存取速度快
-
支持数据库加密
-
轻量级
-
激活实体
-
支持缓存
-
代码自动生成
首先要在Project中的build中添加如下代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
buildscript {
repositories {
jcenter()
}
dependencies {
classpath
'com.android.tools.build:gradle:2.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath
'org.greenrobot:greendao-gradle-plugin:3.2.1'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
|
再在Module中的build添加引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
apply plugin:
'com.android.application'
//使用greendao
apply plugin:
'org.greenrobot.greendao'
android {
compileSdkVersion
25
buildToolsVersion
"25.0.2"
defaultConfig {
applicationId
"com.qianmo.greendaotest"
minSdkVersion
15
targetSdkVersion
25
versionCode
1
versionName
"1.0"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
//greendao配置
greendao {
//版本号,升级时可配置
schemaVersion
1
// daoPackage 'com.qianmo.greendaotest.gen'
// targetGenDir 'src/main/java'
}
buildTypes {
release {
minifyEnabled
false
proguardFiles getDefaultProguardFile(
'proguard-android.txt'
),
'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir:
'libs'
, include: [
'*.jar'
])
androidTestCompile(
'com.android.support.test.espresso:espresso-core:2.2.2'
, {
exclude group:
'com.android.support'
, module:
'support-annotations'
})
compile
'com.android.support:appcompat-v7:25.1.1'
compile
'com.android.support:design:25.1.1'
compile
'org.greenrobot:greendao:3.2.0'
//greendao依赖
testCompile
'junit:junit:4.12'
}
|
这样就配置成功了,接着是简单的使用。
- @Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作
- @Id:对象的Id,使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值
- @Property:可以自定义字段名,注意外键不能使用该属性
- @NotNull:属性不能为空
- @Transient:使用该注释的属性不会被存入数据库的字段中
- @Unique:该属性值必须在数据库中是唯一值
- @Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改
public
class
BaseApplication
extends
Application {
private
static
DaoSession daoSession;
@Override
public
void
onCreate() {
super
.onCreate();
//配置数据库
setupDatabase();
}
/**
* 配置数据库
*/
private
void
setupDatabase() {
//创建数据库shop.db
DaoMaster.DevOpenHelper helper =
new
DaoMaster.DevOpenHelper(
this
,
"shop.db"
,
null
);
//获取可写数据库
SQLiteDatabase db = helper.getWritableDatabase();
//获取数据库对象
DaoMaster daoMaster =
new
DaoMaster(db);
//获取dao对象管理者
daoSession = daoMaster.newSession();
}
public
static
DaoSession getDaoInstant() {
return
daoSession;
}
}
|
这里我们需要创建一个Application,在代码中初始化数据库的基本数据,这里要讲解这下面这三个类
-
DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现
-
DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表
-
DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API
这里注意一下我们要编译一下我们的工程(ctrl+F9),因为上面三个类是运行时创建的,还有相应的Shop中的set和get方法及构造函数