Android greenDao 初识运用

来源:互联网 发布:php怎样保持登录状态 编辑:程序博客网 时间:2024/06/05 16:27

greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。

优势:

  1. 一个精简的库
  2. 性能最大化
  3. 内存开销最小化
  4. 易于使用的 APIs
  5. 对 Android 进行高度优化

使用步骤:

  1. 引入资源
  2. 基础准备
  3. 创建实体
  4. 创建帮助类
  5. 创建初始化工具类
  6. 获取实体使用

在Android Studio中导入相关的包

    //greenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案.    compile 'org.greenrobot:greendao:3.0.1'    compile 'org.greenrobot:greendao-generator:3.0.0'

基础构建准备

build.gradle(Module:app)

//greenDao配置apply plugin: 'org.greenrobot.greendao'buildscript {    repositories {        mavenCentral()    }}/** * schemaVersion--> 指定数据库schema版本号,迁移等操作会用到; * daoPackage --> dao的包名,包名默认是entity所在的包; * targetGenDir --> 生成数据库文件的目录; */greendao {    schemaVersion 1    daoPackage 'com.fly.newstart.greendao.gen'    targetGenDir 'src/main/java'}

build.gradle(Project:项目名)

buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.3'        classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

创建实体User

package com.fly.newstart.greendao.entity;import org.greenrobot.greendao.annotation.Entity;import org.greenrobot.greendao.annotation.Id;import org.greenrobot.greendao.annotation.Transient;import org.greenrobot.greendao.annotation.Generated;/** * 包    名 : com.fly.newstart.greendao.entity * 作    者 : FLY * 创建时间 : 2017/7/17 * <p> * * 描述:(一) @Entity 定义实体 * @nameInDb 在数据库中的名字,如不写则为实体中类名 * @indexes 索引 * @createInDb 是否创建表,默认为true,false时不创建 * @schema 指定架构名称为实体 * @active 无论是更新生成都刷新 * (二) @Id * (三) @NotNull 不为null * (四) @Unique 唯一约束 * (五) @ToMany 一对多 * (六) @OrderBy 排序 * (七) @ToOne 一对一 * (八) @Transient 不存储在数据库中 * (九) @generated 由greendao产生的构造函数或方法 */@Entitypublic class User {    @Id    private Long id;    private String name;    @Transient    private int tempUsageCount;    public String getName() {        return this.name;    }    public void setName(String name) {        this.name = name;    }    public Long getId() {        return this.id;    }    public void setId(Long id) {        this.id = id;    }    @Generated(hash = 873297011)    public User(Long id, String name) {        this.id = id;        this.name = name;    }    @Generated(hash = 586692638)    public User() {    }}

注:只需要书写属性即可,书写后编译一下,及会生成get、set方法并且会在之前准备时设置的com.fly.newstart.greendao.gen目录下生成三个文件:
这里写图片描述

创建帮助类DaoOpenHelper

package com.fly.newstart.greendao.db.helper;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.fly.newstart.greendao.gen.DaoMaster;/** * 包    名 : com.fly.newstart.greendao.db.helper * 作    者 : FLY * 创建时间 : 2017/7/17 * <p> * 描述: */public class DaoOpenHelper extends DaoMaster.OpenHelper {    public DaoOpenHelper(Context context, String name) {        super(context, name);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        super.onUpgrade(db, oldVersion, newVersion);        switch (oldVersion){            case 1:                //不能先删除表//                TestEntityDao.dropTable(db, true);//                TestEntityDao.createTable(db, true);                // 加入新字段 score//                db.execSQL("ALTER TABLE 'TEST_ENTITY' ADD 'SCORE' TEXT;");                break;        }    }}

创建初始化工具类GreenDaoUtils

package com.fly.newstart.greendao.db.utils;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import com.fly.newstart.common.config.BeasConfig;import com.fly.newstart.greendao.DaoApplicatoin;import com.fly.newstart.greendao.db.helper.DaoOpenHelper;import com.fly.newstart.greendao.gen.DaoMaster;import com.fly.newstart.greendao.gen.DaoSession;/** * 包    名 : com.fly.newstart.greendao.dp.utils * 作    者 : FLY * 创建时间 : 2017/7/17 * <p> * 描述: */public class GreenDaoUtils  {    private static final String DEFAULT_DB_NAME = BeasConfig.DB_NAME;    public static GreenDaoUtils instances;    private static Context mContext;    private static String DB_NAME ;    public static DaoSession init(Context context,boolean isDebog){        return init(context,DEFAULT_DB_NAME,isDebog);    }    public static DaoSession init(Context context,String dbName,boolean isDebog){        if (context == null) {            throw new IllegalArgumentException("context can't be null");        }        mContext = context.getApplicationContext();        DB_NAME = dbName;        // 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。        // 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO 已经帮你做了。        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。        // 所以,应该做一层封装,来实现数据库的安全升级。        DaoOpenHelper mHelper = new DaoOpenHelper(context,DEFAULT_DB_NAME);        SQLiteDatabase  db = mHelper.getWritableDatabase();        // 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。        return new DaoMaster(db).newSession();    }    public static DaoSession getDaoSession() {        return DaoApplicatoin.getMainDaoSession();    }}

初始化使用

package com.fly.newstart.greendao;import android.app.Application;import com.fly.newstart.greendao.db.utils.GreenDaoUtils;import com.fly.newstart.greendao.gen.DaoSession;/** * 包    名 : com.fly.newstart.greendao * 作    者 : FLY * 创建时间 : 2017/7/17 * <p> * 描述: GreenDao 初始化操作 */public class DaoApplicatoin extends Application {    /**     * 数据库操作类     */    private static DaoSession sDaoSession;    @Override    public void onCreate() {        super.onCreate();        //数据库初始化        sDaoSession = GreenDaoUtils.init(this,true );    }    /**     * 获取数据库的DaoSession     * @return     */    public static DaoSession getMainDaoSession(){        return sDaoSession;    }}

获取实体使用

UserDao mUserDao = GreenDaoUtils.getDaoSession().getUserDao();    //增    private void insert(){        User mUser = new User((long)2,"anye3");        mUserDao.insert(mUser);//添加一个    }    //删    private void delete(){        //mUserDao.deleteByKey(id);    }    //改    private void update(){        User mUser = new User((long)2,"anye0803");        mUserDao.update(mUser);    }    //查    private void load(){        List<User> users = mUserDao.loadAll();        String userName = "";        for (int i = 0; i < users.size(); i++) {            userName += users.get(i).getName()+",";        }        Log.d(TAG, "load: "+userName);    }
  • @Entity  表明这个实体类会在数据库中生成一个与之相对应的表。
  • @Id  对应数据表中的 Id 字段,有了解数据库的话,是一条数据的唯一标识。
  • @Property(nameInDb = “STUDENTNUM”)  表名这个属性对应数据表中的STUDENTNUM 字段。
  • @Property  可以自定义字段名,注意外键不能使用该属性
  • @NotNull  该属性值不能为空
  • @Transient  该属性不会被存入数据库中
  • @Unique  表名该属性在数据库中只能有唯一值

greenDao官网