1. 什么是GreenDAO?

greenDAO is an open source Android ORM making development for SQLite databases fun again. It relieves developers from dealing with low-level database requirements while saving development time. SQLite is an awesome embedded relational database. Still, writing SQL and parsing query results are quite tedious and time-consuming tasks. greenDAO frees you from these by mapping Java objects to database tables (called ORM, “object/relational mapping”). This way you can store, update, delete, and query for Java objects using a simple object oriented API.

这是greenDAO的自我介绍,大概意思就是greenDAO是针对于Android平台的SQLite的ORM(Object/Relational Mapping)对象关系映射框架。他可以将Java对象映射到数据库表,并帮你封装了增删改查的操作。
GreenDAO

2. 配置GreenDAO

2.1 Your Project

// 在build.gradle(Project:YourProjectName)添加buildscript {    repositories {        mavenCentral()    }    dependencies {        classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'    }}// 在build.gradle(Module:app)添加apply plugin: 'org.greenrobot.greendao'greendao {    targetGenDir 'src/main/java'}dependencies {    compile 'org.greenrobot:greendao:3.1.0'}

2.2 Generator Lib

首先新建一个Module,File->New->New Module…->Java Libarary,命名为GreenDaoGenLib
Android GreenDAO ORM的使用(一) 生成DAO和Bean_第1张图片
创建完成后在项目左侧会出现一个如下图所示的Lib包,且下方Gradle Script中会出现一个对应的gradle配置的地方
Android GreenDAO ORM的使用(一) 生成DAO和Bean_第2张图片

// 在build.gradle(Module:greendaogenlib)中添加dependencies {    compile 'org.greenrobot:greendao-generator:3.1.0'}
// 创建一个类Config用于输出配置public class Config {    static final int VERSION = 1;    static final String DEFAULT_PACKAGE = "org.greendaotest.db.greendao";  // 输出包名    static final String OUTDIR = "/Users/rita/Documents/Projects/GreenDAOTest/app/src/main/java";  // 输出文件位置}

之后打开Generator开始编辑

package org.greendao;import org.greenrobot.greendao.generator.DaoGenerator;import org.greenrobot.greendao.generator.Entity;import org.greenrobot.greendao.generator.Property;import org.greenrobot.greendao.generator.Schema;import org.greenrobot.greendao.generator.ToMany;/** * com.tixmate.tixmate.dataaccess.database.greenDAO * Created by ritaliu. */public class Generator {    private static Schema schema;    public static void main(String[] args) throws Exception {        //创建模式对象,指定版本号和自动生成的bean对象的包名        schema = new Schema(Config.VERSION, Config.DEFAULT_PACKAGE);        //添加所有实体        addEntity();        //调用DaoGenerator().generateAll方法自动生成代码到创建的目录下        new DaoGenerator().generateAll(schema, Config.OUTDIR);    }    private static void addEntity()    {        //添加一个实体,自动生成实体Entity类        Entity account = schema.addEntity("Account");        Entity moment = schema.addEntity("Moment");        /* Account */                    account.addStringProperty("id").primaryKey().getProperty();  //添加ID, 主键        account.addStringProperty("name").notNull();  //添加String类型的name,不能为空        account.addStringProperty("avatarlink");  //添加String类型的Link        /* Moment */         moment.addStringProperty("id").primaryKey().getProperty();        moment.addIntProperty("type").notNull();        moment.addStringProperty("text");        moment.addDateProperty("time").notNull();    }}

上面的代码中简单的生成了两张表Account和Moment,其中个包含一些字段,字段类型可直接使用addXXProperty来定义。一般的ID都是使用Long型的就够了,所以GreenDAO提供了一个addIdProperty()的方法,默认为Long型且会被设置为主键,如不能满足你的需求可以自行添加一个字段,并把他设置为primaryKey。另外GreenDao还提供了字段自增、字段不为空等设置,具体可以参看官网的document。

2. 使用GreenDAO生成实体类和DAOs

上面的Generator编辑完成后,运行这个java类,会看到在之前约定输出的OUTDIR的位置出现了两个包,分别为org.greendaotest.db.bean和org.greendaotest.db.dao,会看到如下的目录结构。
Android GreenDAO ORM的使用(一) 生成DAO和Bean_第3张图片
在bean目录中生成了两个实体类,Account和Moment,在dao目录中生成了两个对应的Dao和一个DaoMaster一个DaoSession。
那么DaoMaster和DaoSession是做什么的呢?官方是这样说的
Android GreenDAO ORM的使用(一) 生成DAO和Bean_第4张图片

DaoMaster: The entry point for using greenDAO. DaoMaster holds the database object (SQLiteDatabase) and manages DAO classes (not objects) for a specific schema. It has static methods to create the tables or drop them. Its inner classes OpenHelper and DevOpenHelper are SQLiteOpenHelper implementations that create the schema in the SQLite database.

DaoSession: Manages all available DAO objects for a specific schema, which you can acquire using one of the getter methods. DaoSession provides also some generic persistence methods like insert, load, update, refresh and delete for entities. Lastly, a DaoSession objects also keeps track of an identity scope. For more details, have a look at the session documentation.

DAOs: Data access objects (DAOs) persists and queries for entities. For each entity, greenDAO generates a DAO. It has more persistence methods than the DaoSession, for example: count, loadAll, and insertInTx.

Entities: Persistable objects. Usually, entities are generated (you do not have to), and are objects representing a database row using standard Java properties (like a POJO or a JavaBean).

2.1 DAOMaster

DAOMaster的作用是使用greenDAO的入口。DaoMaster持有了Database的对象并且管理DAO的类(不是对象)。它包括了建表和删除表的静态方法。它的内部类OpenHelper和DevOpenHelper是SQLiteOpenHelper的实现,实现了在SQLite数据库中创建schema。

2.2 DAOSession

DAOSession管理所有可用的使用特定Schema的DAO对象,你可以从中获得它们的Getter方法。DAOSession提供了一些一般的持久化方法,像一些简单的增删改查操作。并且,DaoSession可以持续追踪一个ID,貌似是用来缓存部分查询结果进行提速的,详情查看Session Documention。

2.3 DAOs

DAOs是数据访问对象,是从数据库存储和查询实体的通道。对于每一个实体,greenDAO都会创建一个DAO。他相对于DaoSession有更多的持久化方法,例如,count,loadAll,insertInTx。

2.4 Entities

Entities是持久化对象。通常,实体根据数据库的字段创建。

2.5 使用

下面是基本的使用方法

DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mContext, "DB_NAME", null);DaoMaster daoMaster = new DaoMaster(helper.getWritableDatabase());DaoSession daoSession = daoMaster.newSession();Account accountDao = daoSession.getAccountDao();

本文只是介绍了使用GreenDAO提供的Generator生成DAO和Bean的方法,简单的生成了两张表,但是既然SQLite是关系型数据库,那么表间怎么能没有关系存在呢?下篇我将介绍如何添加关系,包括1:1, 1:n和n:m三种关系。

更多相关文章

  1. android TabHost 对象报错
  2. Android wifi的WifiInfo对象详解
  3. Android之JAVASe基础篇-面向对象-IO(九)
  4. Android中,把XML文件转换成Object对象的方法
  5. 初学Android,五大布局对象(六)
  6. Android中intent传递对象和Bundle的用法
  7. Android 基本属性绘制文本对象FontMetrics介绍
  8. android Activity之间传递对象
  9. FregClient进程,创建一个BpFregService类型的代理对象

随机推荐

  1. 【android初级】之android布局属性详解
  2. android应用程序键盘事件机制
  3. Android(安卓)ScrollView滚动条
  4. Android(安卓)Layout属性详解
  5. Android应用程序的debug属性
  6. Android基本控件TextView
  7. Android(安卓)Activity 的四种启动模式 l
  8. Android(安卓)ListView 设置
  9. Android(安卓)imageView图片按比例缩放
  10. android 布局学习