Android GreenDAO ORM的使用(一) 生成DAO和Bean

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
greendaogenlib
创建完成后在项目左侧会出现一个如下图所示的Lib包,且下方Gradle Script中会出现一个对应的gradle配置的地方
创建完成

// 在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,会看到如下的目录结构。
greendao生成
在bean目录中生成了两个实体类,Account和Moment,在dao目录中生成了两个对应的Dao和一个DaoMaster一个DaoSession。
那么DaoMaster和DaoSession是做什么的呢?官方是这样说的
Core-Classes

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三种关系。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值