GreenDao官方教程扩展版(2)

GreenDao官方教程扩展版(1)

上次提供了GreenDao生成项目Dao的内容,这次主要是Dao的引用,熟悉Dao操作的童鞋可以自行略过了。

一、添加依赖

两种方法

1. 通过Android Studio自带Maven Central搜索添加:

打开【Project Structure】–>【Your ModuleName】–>【Dependencies】–>【Add】–>【Library Dependencies】在Maven Central搜索框中搜索greenDao,选择de.greenrobot:greendao:2.1.0

2. 通过直接修改build.gradle

具体步骤请参见上篇文章

二、调用生成的Dao类

此处采用官网的例子,具体参见官方Example

  1. 创建数据表
    new DaoMaster.DevOpenHelper(this, “notes-db”, null)
  • 建立数据库连接
    daoMaster = new DaoMaster(db);
    daoSession = daoMaster.newSession();
    noteDao = daoSession.getNoteDao();

  • 具体操作
    private void addNote() {
    String noteText = editText.getText().toString();
    editText.setText(“”);

      final DateFormat df =  DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    
      String comment = "Added on " + df.format(new Date());
    
      Note note = new Note(null, noteText, comment, new Date());
    
      noteDao.insert(note);//插入数据库
    
      Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
    
      cursor.requery();
    
    }
    

除了insert还有updatedelete方法提供使用,查询的话则用getWritableDatabase()来获取SQLiteDatabase对象操作。
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, “notes-db”, null);
SQLiteDatabase noteDb = helper.getWritableDatabase();
Cursor cursor = noteDb.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);//query语法请自行Google or Baidu

三、最后的建议
鉴于架构的松耦合,尽量用自己的类来封装一下这样的Dao类,否则可能导致后期维护异常艰难。

参考:

  1. GreenDao官网
  2. GreenDaoExample
    原文作者:jas0nHu
    原文地址: https://www.jianshu.com/p/100c95e1e4d9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞