greenDao Orm 基本使用<一>

2 篇文章 0 订阅

GreenOrm简介

greenDAO是一个开源的Android ORM使得SQLite数据库开发又有趣。它使开发人员从数据库处理低级需求而节省开发时间。SQLite是一个很棒的嵌入式关系数据库。不过,编写SQL和解析查询结果相当繁琐和耗时的任务。greenDAO释放你从这些通过将Java对象映射到数据库表(称为ORM对象/关系映射)。这样你可以存储、更新、删除和查询的Java对象使用一个简单的面向对象的API。


greenOrm模型

如果有兴趣可以直接访问 greenDao 官网
greenDao 官方github地址: greenDao官方github地址

greenDao orm 基本使用

添加build依赖

project build.gradle中加入

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

module build.gradle中加入

apply plugin: 'org.greenrobot.greendao'

dependencies {
    compile 'org.greenrobot:greendao:3.2.0'
}

创建对象

    @Entity(indexes = {
        @Index(value = "text, date DESC", unique = true)
    })
    public class Note {

        @Id
        private Long id;//notes: id 需要是Long 类型

        @NotNull
        private String text;
        private Date date;
    }

创建好了对象,这时候需要build一下,greendao 会帮助补全 daoSession (操作curd) etc.

application配置

public class App extends Application {
    /** A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher. */
    public static final boolean ENCRYPTED = false;

    private DaoSession daoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
        Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }
}

不要忘记在menifest.xml 中注册application

.实战

  • 获取daosession对象
    DaoSession daoSession = ((App) getApplicationContext()).getDaoSession();
    NoteDao noteDao = daoSession.getNoteDao();
    Note note = new Note(null, noteText, comment, new Date(), NoteType.TEXT);
    noteDao.insert(note);
    Query<Note> notesQuery = noteDao.queryBuilder().orderAsc(NoteDao.Properties.Text).build();
    List<Note> list = notesQuery.list();
    Long noteId = note.getId();

    noteDao.deleteByKey(noteId);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值