Android数据库之GreenDao

GreenDao使用详解
本文介绍了GreenDao作为轻量级ORM解决方案的特点与优势,并详细讲解了其配置方法与基本使用流程,包括实体类定义、数据库管理及增删改查操作。

前言

GreenDao是一个将对象映射到SQLite数据库中的轻量级且快速的ORM解决方案。关于GreenDao的相关信息可以查看官网GreenDao
GreenDao的优势:

  • 一个精简的库
  • 性能最大化
  • 内存开销最小化
  • 易于使用的API
  • 对Android进行高度优化

    GreenDao的配置

    GreenDao 3.0采用注解的方式来定义实体类,通过gradle插件生成相应的代码。

    在项目下build.gradle中进行配置

    classpath ‘org.greenrobot:greendao-gradle-plugin:3.2.2’ // add plugin

在moudle下的单build.gradle中进行配置

compile 'org.greenrobot:greendao:3.2.2' // add library

自定义路径

greendao 
{
    schemaVersion 1
    daoPackage 'com.example.greendaosample.gen'
    targetGenDir 'src/main/java'
}


在gradle的根模块中加入上述代码,就完成了我们的基本配置了。
属性介绍:

  • schemaVersion:指定数据库schema版本号,迁移等操作会用到
  • daoPackage:dao的报名,报名默认是entry所在的包
  • targetGenDir:生成数据库文件的目录

    创建一个User的实体类

    @Entity
    public class User
    {

    @Id 
    private Long id; 
    private String name; 
    @Transient 
    private int tempUsageCount; // not persisted  
    

    }

    MakeProject

    点击Build->ReBuild Project,等待项目编译完成后,User实体类会自动编译,生成get/set方法并且会在daoPackage目录下生成三个文件

GreenDao的使用

设置DBHelper管理数据库

public class DBHelper 
{
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    /**
     * 取得DaoMaster
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context) 
    {
        if (daoMaster == null) 
        {
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,
                "notes.db", null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }
    /**
     * 取得DaoSession
     * @param context
     * @return
     */
    public static DaoSession getDaoSession(Context context) 
    {
        if (daoSession == null) 
        {
            if (daoMaster == null) 
            {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
}

获取UserDao对象:DBHelper.getDaoSession(this).getUserDao();

简单的增删改查实现

增加数据(保存数据)

user=new User( 1l,"张三");
userDao.insert(user);

删除数据

userDao.deleteByKey(1l);

修改数据(更新数据)

user=new User(2l,"lisi");
userDao.update(user);  

查询数据

List<User> users = userDao.loadAll(); 

GreenDao的表

参考:
GreenDaoSample

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值