GreenDao快速入门使用
greenDao简介
greenDAO is a light & fast ORM solution for Android that maps objects to SQLite databases.
官网:http://greenrobot.org/greendao/
github地址:https://github.com/greenrobot/greenDAO
工具和版本
初次撰写于2018-01-19
当前greenDao版本3.2.2
开发工具androidstudio
greenDao如何使用
1、把greenDao添加到你的项目中
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}
2、sync项目后,创建实体
@Entity(indexes = {
@Index(value = "name, age DESC", unique = true)
})
public class User {
@Id
private Long id;
@NotNull
private String name;
private int age;
...
3、配置数据库。
makeproject后,默认在项目的app->build->source->greendao下生成了DaoMaster、DaoSession和实体类的Dao文件。这些文件是greenDao自己生成的,我们在后面会用到。
现在我们需要配置数据库,像这样:
public class MyApplication extends Application {
//是否加密
public static final boolean ENCRYPTED = false;
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
4、现在greenDao基本已经配置好了,我们可以设置greenDao自生成文件的位置和数据库版本:
// In the build.gradle file of your app project:
android {
...
}
greendao {
schemaVersion 1
daoPackage 'com.hyb.greendao.gen'
targetGenDir 'src/main/java'
}
schemaVersion--> 指定数据库schema版本号,迁移等操作会用到;
daoPackage --> dao的包名,包名默认是entity所在的包;
targetGenDir --> 生成数据库文件的目录;
5、基本的数据库增删改查操作
获取Dao类,然后操作。
UserDao userDao = ((MyApplication) getApplication()).getDaoSession().getUserDao();
增:
user = new User(2,"jack");
userDao.insert(user);//添加一个
删:
userDao.deleteByKey(id);
改:
user = new User(2,"tom");
userDao.update(user);
查:
List<User> users = userDao.loadAll();
String userName = "";
for (int i = 0; i < users.size(); i++) {
userName += users.get(i).getName()+",";
}
6、greenDao中的注解
(一) @Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@createInDb 是否创建表,默认为true,false时不创建
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
(二) @Id
(三) @NotNull 不为null
(四) @Unique 唯一约束
(五) @ToMany 一对多
(六) @OrderBy 排序
(七) @ToOne 一对一
(八) @Transient 不存储在数据库中
(九) @generated 由greendao产生的构造函数或方法
最后
更多进阶用法,请详细阅读官方文档。