greenDao Orm 基本使用<一>

来源:互联网 发布:淘宝客怎么套取佣金 编辑:程序博客网 时间:2024/05/02 03:11

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