您的位置:首页 > 其它

GreenDao的使用方法

2016-06-30 11:34 302 查看
GreenDao的使用方法详解----------------------GreenDao orm数据库框架优势:1:性能最大化2:内存开销最小3:API 简单好用4:对android 高度优化5:2.2版本以上还支持加密数据库6:支持protobuf协议存储(protobuf 比json更快,google的优秀产品,因此greendao能很好地与retrofit 2.0结合protobuf网络请求并缓存)greendao的性能远胜于ORMLite ActiveAndroid Xutils等(我亲自测试了的)greendao是两级数据库,分为持久的内存sqlite数据库与内存数据库,如果频繁操作数据库的话,建议是用内存数据库,然后持久到sqlite中,这样的性能远胜于原生的sqlite,即使不使用内存数据库,也几乎与原生sqlite的效率几乎接近。第一步:添加依赖并创建独立session空间
compile 'org.greenrobot:greendao-encryption:2.2.0'
compile 'net.zetetic:android-database-sqlcipher:3.4.0'
第二步骤:创建代码自动生成器 的java工程:并添加生成依赖:
compile 'org.greenrobot:greendao-generator-encryption:2.2.0'
dao的生成器 能自动生成模板orm数据库的模型和表是一一对应的,也就是说通常情况下模型的字段就是表的列:创建表需要依赖实体,但是greendao框架的生成器已经能自动创建模型创建模型或者说创建表 需要用到Schema类:也就是实体添加的容器Schema schema = new Schema(1, "de.greenrobot.daoexample");可以创建一张表对应的版本与实体存放的包接着需要创建实体:需要用到生成器中的一个Entity类,通过schema.addEntity(name) 可以实例化一个指定类名的实体类:如:Entity entity=schema.addEntity("Note");添加完实体,总得需要字段或者说表的列吧添加列也就是实体的字段名称:entity.addIdProperty();//主键entity.addStringProperty("title");//列名
DaoGenerator可以帮我们自动生成entity-表的java代码;
完整代码:
[java] view plain copy print?package com.example;import de.greenrobot.daogenerator.DaoGenerator;import de.greenrobot.daogenerator.Entity;import de.greenrobot.daogenerator.Schema;public class NoteDaoGenerator {public static final int version=1;//数据库版本号public static final String entityPackageName="com.xuan.db.entity";//实体生存的包名public static final String entityClassName="Note";//实体的类名public static final String daoPackageName="com.xuan.db.dao";//指定dao层模板的包//自动生成模板类存放的绝对地址,也就是你的module创建的session文件夹 也就是java-genpublic static final String autoGenerateJavaPath="E:\\Programing\\androidstudio\\workspace\\GitOsc_StudyProject\\db_greendao\\src\\main\\java-gen";public static void main(String[] args) throws Exception {Schema schema = new Schema(version, entityPackageName);schema.setDefaultJavaPackageDao(daoPackageName);//如果不指定 默认与entityPackageName一致Entity entity=schema.addEntity(entityClassName);entity.addIdProperty();//主键entity.addStringProperty("title");//表的地2列 列名entity.addStringProperty("content");//表的地3列 列名entity.addStringProperty("createTime");//表的地4列 列名entity.setClassNameDao("NoteDao");//设置dao类的名称entity.setJavaDoc("auto greenDao generate javaBean by xuan");entity.setTableName("tb_note");//设置表名,默认是entityClassName(NOTE)的大写形式//自动生成java模板类new DaoGenerator().generateAll(schema,autoGenerateJavaPath);}}
执行java main方法,可以在控制台看到如下,表示创建成功,否则您需要检查你的路径是否存在
可以看到在我们指定的文件夹下面已经创建好了这些模型与dao的java类
框架的sqlite语句控制台打印 控制[java] viewplain copyprint?package com.xuan.greendaoencryp;import android.app.Activity;import android.app.Application;import android.os.Bundle;import de.greenrobot.dao.query.QueryBuilder;/*** @author xuanyouwu* @email xuanyouwu@163.com* @time 2015-12-31 10:33*/public class BaseApplication extends Application {@Overridepublic void onCreate() {super.onCreate();QueryBuilder.LOG_SQL = true;QueryBuilder.LOG_VALUES =true;}}dao已经生存好了,接下来就是Orm的增删查改操作了[java] viewplain copyprint?package com.xuan.greendaoencryp.presenter;import android.content.Context;import com.xuan.db.dao.DaoMaster;import com.xuan.db.dao.DaoSession;import com.xuan.db.entity.Note;import java.util.List;/*** @author xuanyouwu* @email xuanyouwu@163.com*/public class NotePresenter {public static final String dbName = "mynote.db";DaoSession daoSession;DaoMaster daoMaster;DaoMaster.DevOpenHelper helper;public NotePresenter(Context context) {helper = new DaoMaster.DevOpenHelper(context, dbName);//创建数据库daoMaster = new DaoMaster(helper.getWritableDatabase());daoSession = daoMaster.newSession();}public long add(Note note) throws Exception {return daoSession.insertOrReplace(note);}public void update(Note note) throws Exception {daoSession.update(note);}public List<Note> loadAll() throws Exception {return daoSession.getNoteDao().loadAll();}public void delete(Note note) throws Exception {daoSession.delete(note);}public void close() {daoSession.clear();daoSession = null;helper.close();helper = null;}}[java] viewplain copyprint?<pre name="code" class="java">package com.xuan.greendaoencryp;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.text.format.DateUtils;import android.view.View;import com.xuan.db.entity.Note;import com.xuan.greendaoencryp.presenter.NotePresenter;import com.xuan.greendaoencryp.utils.LogUtils;import java.util.Calendar;/*** @author xuanyouwu* @email xuanyouwu@163.com* @time 2016-01-07 17:50*/public class NoteActivity extends AppCompatActivity {NotePresenter presenter;Note note;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_note);presenter = new NotePresenter(this);note = new Note();note.setTitle("这是第一个笔记");note.setContent("笔记的内容是greendao");note.setCreateTime(DateUtils.formatElapsedTime(Calendar.getInstance().getTimeInMillis()));}public void onAdd(View v) {try {presenter.add(note);} catch (Exception e) {e.printStackTrace();}}public void onQuery(View v) {try {LogUtils.d("query all:" + presenter.loadAll());} catch (Exception e) {e.printStackTrace();}}public void onUpdate(View v) {note.setCreateTime(DateUtils.formatElapsedTime(Calendar.getInstance().getTimeInMillis()));try {presenter.update(note);} catch (Exception e) {e.printStackTrace();}try {LogUtils.d("update after query all:" + presenter.loadAll());} catch (Exception e) {e.printStackTrace();}}public void onDelete(View v) {try {presenter.delete(note);} catch (Exception e) {e.printStackTrace();}try {LogUtils.d("delete after query all:" + presenter.loadAll());} catch (Exception e) {e.printStackTrace();}}@Overrideprotected void onDestroy() {super.onDestroy();presenter.close();}}-----------------------GreenDao的插入:插入的方式有很多:1:daoSession.getNoteDao().insert(note);//插入note 如果note指定主键与表中已经存在了,就会发生异常(android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: tb_note._id (code 1555))而插入不进去
 daoSession.insert(note); 同上
2: daoSession.getNoteDao().insertOrReplace(note);
      当主键存在的时候会替换,所以能够很好的执行插入操作,推荐daoSession.insertOrReplace(note); 同上
3: 原生的sqlite
     String insertSql = String.format("insert into %s (%s,%s,%s) values('%s','%s','%s')",NoteDao.TABLENAME,NoteDao.Properties.Title.columnName,NoteDao.Properties.Content.columnName,NoteDao.Properties.CreateTime.columnName,note.getTitle(),note.getContent(),note.getCreateTime());   daoSession.getDatabase().execSQL(insertSql);
4:批量插入
   public void insertBatch(List<Note> notes){    daoSession.getNoteDao().insertInTx(notes);}
GreenDao的更新操作
1:单条更新(唯一性条件是主键相同)public void update(Note note) throws Exception {daoSession.update(note);//  daoSession.getNoteDao().update(note);}
2:批量更新
   //批量更新public void updateBatch(List<Note> notes) throws Exception {daoSession.getNoteDao().updateInTx(notes);}
3:原生sql:  
   public void updateSql(String sql){//  daoSession.getDatabase().execSQL("update .....");daoSession.getDatabase().execSQL(sql);}
GreenDao 的删除操作
1:单条删除(唯一性是主见相同)
   public void delete(Note note) throws Exception {      daoSession.delete(note);// daoSession.getNoteDao().delete(note);}
2: 单条删除 指定主键删除
   public void delete(long id) {daoSession.getNoteDao().deleteByKey(id);}
3:批量删除
  public void deleteBatch(List<Note> notes) {daoSession.getNoteDao().deleteInTx(notes);}
4:批量按主键删除
  // 批量按主键删除public void deleteBatchByKey(List<Long> pkIds) {daoSession.getNoteDao().deleteByKeyInTx(pkIds);}
5:删除所有
   public void deleteAll() throws Exception {daoSession.deleteAll(Note.class);//   daoSession.getNoteDao().deleteAll();}
6:原始sqlite语句
daoSession.getDatabase().execSQL(deletesql);
GreenDao 查询操作 也是最复杂的
1:单条查询
[java] view plain copy print?//按主键查询public Note query(long pk) throws Exception {// daoSession.getNoteDao().load(pk);//按主见查询//daoSession.getNoteDao().load(rowId);//按行号查询return daoSession.load(Note.class, pk);}2: QueryBuilder 复合查询
  [java] view plain copy print?public List<Note> queryBuider() throws Exception {//select from tb_note where Content like 'greendao'return daoSession.getNoteDao().queryBuilder().where(NoteDao.Properties.Content.like("greendao")).build().list();}
[java] viewplain copyprint?public long queryBuider2(long pk) throws Exception {//select count(*) from tb_note where Content like 'greendao'return daoSession.getNoteDao().queryBuilder().where(NoteDao.Properties.Content.like("greendao")).buildCount().count();}[java] viewplain copyprint?public void queryBuider3() throws Exception {Cursor cursor = null;try {//CursorQuery 部分查询CursorQuery greendao = daoSession.getNoteDao().queryBuilder().where(NoteDao.Properties.Content.like("greendao")).buildCursor();cursor = greendao.query();while (cursor.moveToNext()) {long id = cursor.getInt(0);String title = cursor.getString(1);String content = cursor.getString(2);String time = cursor.getString(cursor.getColumnIndex(NoteDao.Properties.CreateTime.columnName));}} finally {if (cursor != null)cursor.close();}}3:查询所有:[java] viewplain copyprint?public void queryAll(){daoSession.loadAll(Note.class);daoSession.queryBuilder(Note.class).build().list();daoSession.getNoteDao().queryBuilder().build().list();daoSession.getNoteDao().loadAll();}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: