开始使用GreenDao
本文将通过一个简单的浏览greenDAO示例项目DaoExample。你可以在GitHub上克隆并运行代码或者直接查看项目中的文件。
Daoexample是一个记笔记的简单的Android应用程序。你可以添加文本记录笔记,也可以通过点击删除笔记。
Note实体及DAO类
如下代码中,你可以发现一个Note的实体类Note.java,它被存储在数据库中,其中包含id、text、date等属性。
@Entity(indexes = {
@Index(value = "text, date DESC", unique = true)
})
public class Note {
@Id
private Long id;
@NotNull
private String text;
private Date date;
...
通常,数据库中一行代表某种类型实体的一个实例,每一列代表实体的一个属性。
现在,你可以使用Android studio中的Build > Make project来构建项目,这个操作将会是greenDao产生一系列Dao类,如NoteDao.java,这些类将Note实例存入数据库。
插入或删除notes
您可以查看NoteActivity类,来学习如何添加笔记。首先我们需要在onCreate()中为Note.class准备相应的Dao对象,如下:
// get the note DAO
DaoSession daoSession = ((App) getApplication()).getDaoSession();
noteDao = daoSession.getNoteDao();
当使用者点击按钮触发addNote()方法时,会创建一个Note实例并通过先前创建的Dao对象的insert()方法添加到数据库中:
Note note = new Note();
note.setText(noteText);
note.setComment(comment);
note.setDate(new Date());
note.setType(NoteType.TEXT);
noteDao.insert(note);
Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
当我们创建note实例时不能传递id给该实例,因为id石油数据库来决定的。在存储数据时,数据库会自动设置id并通过insert()方法返回。
删除note的方法如下:
noteDao.deleteByKey(id);
更新note等方法
在修改note属性后,调用Dao的update()方法便可更新数据库相应笔记:
note.setText("This note has changed.");
noteDao.update(note);
设置数据库
上面介绍了怎样生成实体相应的Dao类以及如何使用Dao类,那么怎样初始化GreenDAO和数据库呢?一般你可以在Application类中来初始化DaoSession类:
DevOpenHelper helper = new DevOpenHelper(this, "notes-db");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
Build项目产生的DaoMaster.class中含有一个内部类DevOpenHelper.class,这个内部类继承自OpenHelper.class,这样避免我们再去书写“CREATE TABLE”等创建表的声明。