GreenDao3.2的基本使用方法

前言

GreenDao是一款操作数据库的神器,经过了2.0版本的升级后,已经被广泛的开发者使用。确实是很好用,入门简单,可以剩去了数据库的建表操作和数据库SQL的编写,博主用了一次之后爱不释手,和以前的数据库操作一大堆的代码将它缩成了一句话,舒服.

GreenDao3.2的简介

认识GreenDao之前必须知道ORM(Object Relation Mapping对象关系映射),其表现形式就是通过GreenDao将数据库和Bean对象关联起来,其表现形式如下图

GreenDao之所以很流行,跟它的优点是息息相关的,从官网中可以看到这样一张图,其表示了在主流的ORM第三方库中,其对数据库操作的速度是最快的

不仅如此,其优点还包括有以下几点

  1. 存取速度快

  2. 支持数据库加密

  3. 轻量级

  4. 激活实体

  5. 支持缓存

  6. 代码自动生成

GreenDao3.2的配置

GreenDao的配置很简单,不过需要注意的是,有些人按照正确的配置后却频频出错,个人也经历过,最后的原因是网络有问题。因为校园网的DNS服务很差,所以解析不到GreenDao的依赖网站

一、需要在工程(Project)的build.gradle中添加依赖

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        //GreenDao3依赖
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

二、在项目(Module)的build.gradle中添加依赖

apply plugin: 'com.android.application'
//使用greendao

apply plugin: 'org.greenrobot.greendao'android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.handsome.didi"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    //greendao配置
    greendao {
        //版本号,升级时可配置
        schemaVersion 1                             
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    //greendao依赖
    compile 'org.greenrobot:greendao:3.2.0'
}

到这里就配置成功了

一、创建Bean对象(表名和字段名)

@Entity
public class Bean {

    /**
     * 表示为购物车列表
     */
    public static final int TYPE_CART = 0x01;
    /**
     * 表示为收藏列表
     */
    public static final int TYPE_LOVE = 0x02;

    /**
     * 不能用int
     */
    @Id(autoincrement = true)
    private Long id;
    /**
     * 商品名称
     */
    @Unique
    private String name;
    /**
    *商品价格
    */
    @Property(nameInDb = "price")
    private String price;
    /**
     * 已售数量
     */
    private int sell_num;
    /**
     * 图标url
     */
    private String image_url;
    /**
     * 商家地址
     */
    private String address;
    /**
     * 商品列表类型
     */
    private int type;
}

点击Build后make project后GreenDao会自动帮你生成get/set方法如下:

package com.tongseng.sqlitedemo.generate;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;
import org.greenrobot.greendao.annotation.Unique;
import org.greenrobot.greendao.annotation.Generated;

/**
 * com.tongseng.sqlitedemo.generate
 *
 * @author Administrator
 * @date 2018/3/21
 */
@Entity
public class Bean {

    /**
     * 表示为购物车列表
     */
    public static final int TYPE_CART = 0x01;
    /**
     * 表示为收藏列表
     */
    public static final int TYPE_LOVE = 0x02;

    /**
     * 不能用int
     */
    @Id(autoincrement = true)
    private Long id;
    /**
     * 商品名称
     */
    @Unique
    private String name;
    /**
    *商品价格
    */
    @Property(nameInDb = "price")
    private String price;
    /**
     * 已售数量
     */
    private int sell_num;
    /**
     * 图标url
     */
    private String image_url;
    /**
     * 商家地址
     */
    private String address;
    /**
     * 商品列表类型
     */
    private int type;
    @Generated(hash = 139605306)
    public Bean(Long id, String name, String price, int sell_num, String image_url,
            String address, int type) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.sell_num = sell_num;
        this.image_url = image_url;
        this.address = address;
        this.type = type;
    }
    @Generated(hash = 80546095)
    public Bean() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPrice() {
        return this.price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public int getSell_num() {
        return this.sell_num;
    }
    public void setSell_num(int sell_num) {
        this.sell_num = sell_num;
    }
    public String getImage_url() {
        return this.image_url;
    }
    public void setImage_url(String image_url) {
        this.image_url = image_url;
    }
    public String getAddress() {
        return this.address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getType() {
        return this.type;
    }
    public void setType(int type) {
        this.type = type;
    }
}

这里需要注意的是,创建完成之后,需要build gradle来完成我们的代码自动生成。自动生成的代码有

1. Bean实体的构造方法和get、set方法

2. DaoMaster、DaoSession、DAOS类

这里对Bean对象的注释进行解释

  1. @Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作

  2. @Id:对象的Id,使用Long类型作为EntityId,否则会报错。(autoincrement = true)表示主键会自增,如果false就会使用旧值

  3. @Property:可以自定义字段名,注意外键不能使用该属性

  4. @NotNull:属性不能为空

  5. @Transient:使用该注释的属性不会被存入数据库的字段中

  6. @Unique:该属性值必须在数据库中是唯一值

  7. @Generated:编译后自动生成的构造函数、方法等的注释,提示构造函数、方法等不能被修改

二、创建数据库(数据库名)

数据库的表名和字段都建好了,下面差个数据库的创建,下面通过传统和GreenDao的比较来体验其优点

public class BaseApplication extends Application {

    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        //配置数据库
        setupDatabase();
    }

    /**
     * 配置数据库
     */
    private void setupDatabase() {
        //创建数据库shop.db"
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "shop.db", null);
        //获取可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoInstant() {
        return daoSession;
    }
}

可以发现,GreenDao已经将我们的数据库创建缩成几句话,代码会自动将Bean对象创建成表,不再是传统的手写SQL语句。这里的数据库创建只需要在Application中执行一次即可,这里对几个类进行解释

  1. DevOpenHelper:创建SQLite数据库的SQLiteOpenHelper的具体实现

  2. DaoMaster:GreenDao的顶级对象,作为数据库对象、用于创建表和删除表

  3. DaoSession:管理所有的Dao对象,Dao对象中存在着增删改查等API

由于我们已经创建好了DaoSession和Bean的Bean对象,编译后会自动生成我们的BeanDao对象,可通过DaoSession获得

BeanDao dao = daoSession.getBeanDao();

这里的Dao(Data Access Object)是指数据访问接口,即提供了数据库操作一些API接口,可通过dao进行增删改查操作

三、数据库的增删改查

数据库的表名、字段、数据库都建好了,下面就通过GreenDao对数据库进行操作

public class LoveDao {

    /**
     * 添加数据,如果有重复则覆盖
     *
     * @param shop
     */
    public static void insertLove(Shop shop) {
        BaseApplication.getDaoInstant().getShopDao().insertOrReplace(shop);
    }

    /**
     * 删除数据
     *
     * @param id
     */
    public static void deleteLove(long id) {
        BaseApplication.getDaoInstant().getShopDao().deleteByKey(id);
    }

    /**
     * 更新数据
     *
     * @param shop
     */
    public static void updateLove(Shop shop) {
        BaseApplication.getDaoInstant().getShopDao().update(shop);
    }

    /**
     * 查询条件为Type=TYPE_LOVE的数据
     *
     * @return
     */
    public static List<Shop> queryLove() {
        return BaseApplication.getDaoInstant().getShopDao().queryBuilder().where(ShopDao.Properties.Type.eq(Shop.TYPE_LOVE)).list();
    }

    /**
     * 查询全部数据
     */
    public static List<Shop> queryAll() {
        return BaseApplication.getDaoInstant().getShopDao().loadAll();
    }
}

效果很明显,GreenDao的封装更加短小精悍,语义明朗,下面对GreenDao中Dao对象其他API的介绍

  • 增加单个数据

    • getShopDao().insert(shop);

    • getShopDao().insertOrReplace(shop);

  • 增加多个数据

    • getShopDao().insertInTx(shopList);

    • getShopDao().insertOrReplaceInTx(shopList);

  • 查询全部

    • List< Shop> list = getShopDao().loadAll();

    • List< Shop> list = getShopDao().queryBuilder().list();

  • 查询附加单个条件

    • .where()

    • .whereOr()

  • 查询附加多个条件

    • .where(, , ,)

    • .whereOr(, , ,)

  • 查询附加排序

    • .orderDesc()

    • .orderAsc()

  • 查询限制当页个数

    • .limit()

  • 查询总个数

    • .count()

  • 修改单个数据

    • getShopDao().update(shop);

  • 修改多个数据

    • getShopDao().updateInTx(shopList);

  • 删除单个数据

    • getTABUserDao().delete(user);

  • 删除多个数据

    • getUserDao().deleteInTx(userList);

  • 删除数据ByKey

    • getTABUserDao().deleteByKey();

当然,看到其他博客的方法,也可以把对greenDAO的调用封装成为一个单例模式,方便调用。

ublic class GreenDaoManager {

    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private static GreenDaoManager mInstance; //单例

    private GreenDaoManager(){
        if (mInstance == null) {
            DaoMaster.DevOpenHelper devOpenHelper = new
                    DaoMaster.DevOpenHelper(MyApplication.getContext(), "user1-db", null);//此处为自己需要处理的表
            mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
            mDaoSession = mDaoMaster.newSession();
        }
    }

    public static GreenDaoManager getInstance() {
        if (mInstance == null) {
            synchronized (GreenDaoManager.class) {//保证异步处理安全操作

                if (mInstance == null) {
                    mInstance = new GreenDaoManager();
                }
            }
        }
        return mInstance;
    }

    public DaoMaster getMaster() {
        return mDaoMaster;
    }
    public DaoSession getSession() {
        return mDaoSession;
    }
    public DaoSession getNewSession() {
        mDaoSession = mDaoMaster.newSession();
        return mDaoSession;
    }
}

在Application中配置

public class BaseApplication extends Application {

    private static Context mContext;
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        //greenDao全局配置,只希望有一个数据库操作对象
        GreenDaoManager.getInstance();
    }
    public static Context getContext() {
        return mContext;
    }
}

下面为一些常用的注解使用方式:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值