标签:
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代码;
完整代码:
- 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";
-
-
- public 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);
- Entity entity=schema.addEntity(entityClassName);
- entity.addIdProperty();
- entity.addStringProperty("title");
- entity.addStringProperty("content");
- entity.addStringProperty("createTime");
- entity.setClassNameDao("NoteDao");
- entity.setJavaDoc("auto greenDao generate javaBean by xuan");
- entity.setTableName("tb_note");
-
- new DaoGenerator().generateAll(schema,autoGenerateJavaPath);
- }
- }
执行java main方法,可以在控制台看到如下,表示创建成功,否则您需要检查你的路径是否存在
可以看到在我们指定的文件夹下面已经创建好了这些模型与dao的java类
框架的sqlite语句控制台打印 控制
-
package com.xuan.greendaoencryp;
-
-
import android.app.Activity;
-
import android.app.Application;
-
import android.os.Bundle;
-
-
import de.greenrobot.dao.query.QueryBuilder;
-
-
-
-
-
-
-
public class BaseApplication extends Application {
-
-
@Override
-
public void onCreate() {
-
super.onCreate();
-
QueryBuilder.LOG_SQL = true;
-
QueryBuilder.LOG_VALUES =true;
-
}
-
}
dao已经生存好了,接下来就是Orm的增删查改操作了
-
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;
-
-
-
-
-
-
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;
-
}
-
}
-
<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;
-
-
-
-
-
-
-
public class NoteActivity extends AppCompatActivity {
-
-
NotePresenter presenter;
-
Note note;
-
-
@Override
-
protected 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();
-
}
-
}
-
-
@Override
-
protected 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:单条查询
-
- public Note query(long pk) throws Exception {
-
-
- return daoSession.load(Note.class, pk);
- }
2: QueryBuilder 复合查询
- public List<Note> queryBuider() throws Exception {
-
- return daoSession.getNoteDao().queryBuilder().where(NoteDao.Properties.Content.like("greendao")).build().list();
- }
-
public long queryBuider2(long pk) throws Exception {
-
-
return daoSession.getNoteDao().queryBuilder().where(NoteDao.Properties.Content.like("greendao")).buildCount().count();
-
}
-
public void queryBuider3() throws Exception {
-
Cursor cursor = null;
-
try {
-
-
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:查询所有:
-
public void queryAll()
-
{
-
daoSession.loadAll(Note.class);
-
daoSession.queryBuilder(Note.class).build().list();
-
daoSession.getNoteDao().queryBuilder().build().list();
-
daoSession.getNoteDao().loadAll();
-
}
GreenDao的使用方法
标签:
原文地址:http://blog.csdn.net/qq_15807167/article/details/51789003