您的位置:首页 > 其它

GreenDao使用入门

2015-11-16 16:11 417 查看

GreenDao使用入门

她是一个ORM框架。

常见的一些ORM框架:

- ORMLite

- GreenDao

- ormndroid

- androrm

ORM(Object Relation Mapping):对象关系模型。用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上说,它其实是创建了一个可在编程语言里使用的“虚拟对象数据库”。ORM作为项目中间件形式实现数据在不同场景下数据关系映射,对象关系映射是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。

目前网络上流传的大部分是用Eclispe部署,本文将介绍GreenDao的部署与自动生成器的使用.

开发工具使用android studio 1.3.1版本.

1 获取GreenDao

Github
https://github.com/greenrobot/greenDAO

你可以下载源码,自己构建工程编译来使用,也可以使用gradle来自动构建:

Gradle dependency for your Android :(添加greendao依赖)

compile 'de.greenrobot:greendao:2.0.0'


Gradle dependency for your Java generator project:(添加greendao自动生成器依赖)

compile 'de.greenrobot:greendao-generator:2.0.0'


2 使用greendao-generator生成代码

1 新建module,类型为Java-Library:



2 打开mydao的build.gradle



3 为mydao添加greenDao和greendao-generator依赖



可以看到,我们添加了个依赖库,一个是greendao,一个是generator。

你必须两个库都添加。

4 编写MyDaoGenerator,准备生成自己的Dao相关类

public class MyDaoGenerator {
public static void main(String args[]) throws Exception {
//指定数据库版本和包名
Schema schema = new Schema(1, "cn.example.dao");

//添加各种数据对象
addReportDao(schema);
addRecordDao(schema);

//生成到指定的目录下
String filePath = "/app/src/main/java";
File dir = new File("");
File tarDir = new File(dir.getAbsoluteFile()+filePath);
//或者,指定绝对路径,但目录必须提前新建好
//tarDir = new File("F:\count-dao-gen");
new DaoGenerator().generateAll(schema, tarDir.getAbsolutePath());
}
private static void addReportDao( Schema schema){
//创建数据类DataObject1
Entity note = schema.addEntity("DataObject1");
note.addIdProperty();
//添加各种属性,你懂的
note.addDoubleProperty("property1").notNull();
note.addDoubleProperty("property2").notNull();
note.addStringProperty("property3").notNull();
note.addDateProperty("property4").notNull();
note.addDateProperty("property5").notNull();
}
private static void addRecordDao( Schema schema){
Entity note = schema.addEntity("DataObject2");
note.addIdProperty();
note.addBooleanProperty("ppp2");
note.addDoubleProperty("ppp3").notNull();
note.addStringProperty("ppp4").notNull();
note.addDateProperty("ppp5").notNull();
}
}


run之,可得



查看生成的代码



简直太爽了有没有,数据对象类和对应的DAO自动生成。

3 使用greenDao

具体使用网络上有很多,就不一一列举了,贴个插入数据的代码吧.

插入:

DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
DataObject1Dao data1Dao = daoSession.getDataObject1Dao();
//自己写个data对象来测试
DataObject1 data = new DataObject1(1, property1, property2, property3, property4, property5);
noteDao.insert(data);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: