预生成代码并且创建表
首先看代码,在src-gen源码目录中,你会发现已经存在的组件:
- Node.java是对node的一个简单封装。
- NoteDao.java是Dao类,用它来操作Node对象,进行CURD操作。
你可以运行DaoExampleGenerator工程来生成Note和NoteDao,但是咱们先不管DaoExampleGenerator。用DaoMaster这个类你可以方便的创建SQLiteOpenHelper:
1 2 |
new DaoMaster.DevOpenHelper(this, "notes-db", null) |
正如你看到的一样,你不需要去编写“CREATE TABLE”这样的SQL脚本,这一切都有greenDao替你完成。
greenDao插入和删除(greenDao Inserting and deleting nodes)
前面的动作已经为我们创建了note表,这个时候我们就可以将插入几条记录到数据库了。这个动作在NoteActivity类中完成。在onCreate方法中准备一个Dao对象。
1 2 3 4 |
daoMaster = new DaoMaster(db); daoSession = daoMaster.newSession(); noteDao = daoSession.getNoteDao(); |
然后看addNote方法中插入新纪录到数据库的代码
1 2 3 4 |
Note note = new Note(null, noteText, comment, new Date()); noteDao.insert(note); Log.d("DaoExample", "Inserted new note, ID: " + note.getId()); |
上面的代码中只是创建了一个java对象然后调用Dao的insert方法。当insert方法返回之后,数据库中记录的id就和刚才的对象绑定了,可以查看日志的输出。
greendao删除记录也非常简单,看onListItemClick方法中的代码
noteDao.deleteByKey(id);
你还可以自己尝试一下Dao中的其他方法比如loadAll和update。
数据模型和代码生成
为了扩展note或者创建新的entities,你需要学习DaoExampleGeneration工程。它包含一个简单的数据模型定义:
1 2 3 4 5 6 7 8 |
Schema schema = new Schema(1, "de.greenrobot.daoexample"); Entity note= schema.addEntity("Note"); note.addIdProperty(); note.addStringProperty("text").notNull(); note.addStringProperty("comment"); note.addDateProperty("date"); new DaoGenerator().generateAll(schema, "../DaoExample/src-gen"); |
上面的代码是模型对象,可以用来添加entities实体类,一个entitiy类绑定一个数据库表。entity包含许多的属性,用来映射数据表的列。如果所有的模型都定义完了,就可以运行代码生成实体类和对应的Dao文件了。
为什么greenDao性能好,原因之一就是,代码预生成,而不是运行时读取解析注解的方式。
Next steps
通过上面的介绍,你已经对greenDao有了一个初步的影响,接下来就是自己动手实践了。你也可以继续查看文档。