greenDAO使用教程

greenDAO官方主页:http://greendao-orm.com/

官方主页新地址:http://greenrobot.org/greendao/

一、greenDAO是一个轻量、快速的ORM解决方案,它将对象映射到SQLite数据库。

二、主页

greenDAO是一个帮助Android开发者将数据存到SQLite中的一个开源项目。SQLite是一个很好的嵌入式关系数据库。然而,开发它需要大量额外的工作。编写SQL和解析查询结果是相当繁琐的任务。greenDAO将会为你做这些工作:它把Java对象映射到数据表(通常被叫做ORM:https://en.wikipedia.org/wiki/Object-relational_mapping)。这样,你可以使用一个简单的面向对象的接口来存储、更新、删除和查询Java对象。将时间集中在真正的问题上。

greenDAO的主要设计目标

·性能最大化(对于Android来说,可能是最快的ORM)

·很容易使用APIs

·对Android高度优化

·最小的内存开销

·较小的文件体积,将注意力集中在重点上

哪些人正在使用greenDAO?

几个顶级Android应用程序都依赖greenDAO。这些应用程序中的几个超过了1000万次的安装。这展示了行业可靠性。你可以在APPBrainhttp://www.appbrain.com/stats/libraries/details/greendao/greendao)上看看目前的统计数据。

三、特性

实体/关系映射(ORM)

greenDAO的本质是提供一个保存在关系型数据库SQLite中的数据的面向对象接口。只定义数据模型,然后greenDAO将会创建Java数据对象(实体)和DAOs(数据访问对象:https://en.wikipedia.org/wiki/Data_access_object)。这会为你节省很多无聊的代码,那些代码仅仅是来回移动数据。除此之外,greendao提供了一些高级的ORM功能http://greendao-orm.com/2011/08/12/greendao-2nd-preview/),像一个session缓存、预先加载,和活跃实体。

性能

greenDAO在性能方面没有做任何的妥协。数据库擅长存储大量数据,因此,可以使事件速度加快。使用greenDAO,大量实体以每秒数千实体(http://greendao-orm.com/2011/10/23/current-performance-figures/)的速率被插入、更新和加载。

greenDAO和比较流行的ORM工具集的比较:对于给定相同的实体,greenDAO插入和更新实体的速度是ORMLite的两倍,并且在加载实体方面,它的加载速度比ORMLite快4.5倍。在一些特殊的应用中,加载速度是至关重要的。


(数据和图表更新于2011年10月23日)

除了高性能的greenDAO核心,像会话高速缓存和智能热加载技术的特性也会对性能有额外的提升。

轻量的库

greendao核心库的大小小于100K,所以添加greendao不会过于加大你的APK文件大小。

活动实体

如果你想的话,实体可以处于“活动的”状态:活动实体可以解决显而易见的关系(你只需要调用getter方法),并且有更新、删除和刷新方法,这些方法为持久性功能提供了便利的访问方式。

协议缓冲区支持

greenDAO可以将协议缓冲区(protobuf:https://github.com/google/protobuf)对象直接写入数据库中。如果你想通过protobuf与你的服务器对话,你不需要任何的映射。普通实体的所有持久化操作对protobuf对象都是可用的。我们相信这是greenDAO的一个独一无二的特性。

代码生成

greenDAO将会生成Java数据对象(实体)和DAO对象。这些DAO对象被用来让实体有最好的合理映射射方式。

未来计划:生成adapter,也可能包括一些有CRUD操作的activity。

开源

greenDAO的源代码被放在了githubhttps://github.com/greenrobot/greenDAO)上,并且是完全可用的。源代码树中也包含了一个JUnit测试套件,它使用了greenDAO所有的特性。因此,它是一个学习greenDAO很好的方式。

支持

greenDAO开源,且由它的开发者和社区共同支持(http://greendao-orm.com/contact-support/)。除此之外,greenDAO的创造者greenrobothttp://greenrobot.de/)能够为你的特殊需求提供商业支持。

四、使用入门

1、新建项目及在main目录下新建文件夹java-gen,用于存放自动生成的bean和dao;

2、buid.gradle的配置,添加

sourceSets{

main{

java.srcDirs=['src/main/java','src/main/java-gen']

}

}

以及引用:

compile'de.greenrobot:greendao-generator:2.1.0'

compile'de.greenrobot:greendao:2.1.0'

3、创建模式对象,添加数据库表(实体类):

importorg.greenrobot.greendao.generator.DaoGenerator;

importorg.greenrobot.greendao.generator.Entity;

importorg.greenrobot.greendao.generator.Schema;

/**

* Created by sunny on 2016/8/12 0012.

*/

public class Generator{

public static void main(String[]args) throws Exception{

int version=1;

String defaultPackage="test.greenDAO.bean";

//创建模式对象,指定版本号和自动生成的bean对象的包名

Schema schema=new Schema(version,defaultPackage);

//指定自动生成的dao对象的包名,不指定则都DAO类生成在"test.greenDAO.bean"包中schema.setDefaultJavaPackageDao("test.greenDAO.dao");

//添加实体

addEntity(schema);

//自动生成的bean和dao存放的java-gen路径,注意要改成自己的

String outDir="E:/test/GreenDAO_sunnyDemo/app/src/main/java-gen";

//调用DaoGenerator().generateAll方法自动生成代码到之前创建的java-gen目录下

new DaoGenerator().generateAll(schema,outDir);

}

private static void addEntity(Schema schema) {

//添加一个实体,则会自动生成实体Entity

Entity entity=schema.addEntity("Entity");

//指定表名,如不指定,表名则为Entity(即实体类名)

entity.setTableName("student");

//给实体类中添加属性(即给test表中添加字段)

entity.addIdProperty().autoincrement();//添加Id,自增长

entity.addStringProperty("name").notNull();//添加String类型的name,不能为空

entity.addIntProperty("age");//添加Int类型的

ageentity.addDoubleProperty("score");//添加Doublescore

}

}

4、运行Generator类代码,会自动生成bean和dao在刚才创建的java-gen文件夹下:

5、新建BaseApplication继承Application,并在Manifest文件中配置:

importandroid.app.Application;

importandroid.database.sqlite.SQLiteDatabase;

importtest.greenDAO.dao.DaoMaster;

importtest.greenDAO.dao.DaoSession;

/**

* Created by sunny on 2016/8/12 0020.

*/

public class BaseApplication extends Application{

public DaoSession daoSession;

public SQLiteData basedb;

public DaoMaster.DevOpenHelper helper;

public DaoMaster daoMaster;

@Override

public void onCreate() {

super.onCreate();

setupDatabase();

}

private void setupDatabase() {

//通过DaoMaster的内部类DevOpenHelper,你可以得到一个便利的SQLiteOpenHelper对象。//可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的SQL语句,因为greenDAO已经帮你做了。//注意:默认的DaoMaster.DevOpenHelper会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。//所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。

helper=new DaoMaster.DevOpenHelper(this,Constants.DB_NAME,null);

db=helper.getWritableDatabase();

//注意:该数据库连接属于DaoMaster,所以多个Session指的是相同的数据库连接。

daoMaster=new DaoMaster(db);

daoSession=daoMaster.newSession();

}

public DaoSession getDaoSession() {

return daoSession;

}

public SQLiteDatabase getDb() {

return db;

}

}

6、接下来准备对数据库进行相关操作:

(1)先写一下activity_main的布局:

android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginleft="5dp"

android:layout_marginright="5dp"

android:layout_margintop="10dp"

android:orientation="horizontal">

android:id="@+id/tv_id"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="id:0">

android:id="@+id/et_name"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:hint="name">

android:id="@+id/et_age"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:hint="age">

android:id="@+id/et_score"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:hint="score">

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

android:id="@+id/btn_add"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="add">

android:id="@+id/btn_delete"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="delete">

android:id="@+id/btn_update"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="update">

android:id="@+id/btn_query"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="query">

android:id="@+id/lv_list"

android:layout_width="match_parent"

android:layout_height="match_parent">

(2)在MainActivity类上编写代码:

importandroid.app.Activity;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.os.Bundle;

importandroid.text.TextUtils;

importandroid.view.View;

importandroid.widget.AdapterView;

importandroid.widget.EditText;

importandroid.widget.ListView;

importandroid.widget.TextView;

importandroid.widget.Toast;

importjava.util.List;

importde.greenrobot.dao.query.Query;

importtest.greenDAO.bean.Entity;

importtest.greenDAO.dao.EntityDao;

public class MainActivity extends Activity{

privateTextView tv_id;

private EditText et_name;

private EditText et_age;

private EditText et_score;

private ListView lv_list;

private Cursor cursor;

private BaseAdapter adapter;

private longid;

private String name;

private Integer age;

private Double score;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//初始化控件

initView();

//listView列表根据Id降序排序

String orderBy=EntityDao.Properties.Id.columnName+"

DESC";

//查询,得到

cursor cursor=getDb().query(getEntityDao().getTablename()

,getEntityDao().getAllColumns(),null,null,null,null,orderBy);

//初始化适配器

initAdapter();

}

private void initView() {

tv_id=(TextView) findViewById(R.id.tv_id);

et_name=(EditText) findViewById(R.id.et_name);

et_age=(EditText) findViewById(R.id.et_age);

et_score=(EditText) findViewById(R.id.et_score);

lv_list=(ListView) findViewById(R.id.lv_list);

}

private void initAdapter() {

adapter=new BaseAdapter(this,cursor);

lv_list.setAdapter(adapter);

lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterViewadapterView,Viewview,intposition,longid_index) {

id=cursor.getLong(0);

tv_id.setText("id: "+id);

et_name.setText(cursor.getString(1));

et_age.setText(cursor.getInt(2)+"");

et_score.setText(cursor.getDouble(3)+"");

}

});

}

private EntityDao getEntityDao() {

//通过BaseApplication类提供的getDaoSession()获取具体Dao

return((BaseApplication)this.getApplicationContext()).getDaoSession().getEntityDao();

}

private SQLiteDatabase getDb() {

//通过BaseApplication类提供的getDb()获取具体db

return((BaseApplication)this.getApplicationContext()).getDb();

}

/**

*添加*/

public void addEntity(View view) {

name=et_name.getText().toString().trim();

age=Integer.parseInt(et_age.getText().toString().trim());

score=Double.parseDouble(et_score.getText().toString().trim());

if(!TextUtils.isEmpty(name)) {

Entity entity=new Entity(null,name,age,score);

//面向对象添加表数据

getEntityDao().insert(entity);

cursor.requery();//刷新

}

else{

Toast.makeText(MainActivity.this,"name不能为空",Toast.LENGTH_SHORT).show();

}

}

/***根据id删除*/

public void deleteEntity(View view) {

getEntityDao().deleteByKey(id);

cursor.requery();

}

/**

*更新*/

public void updateList(View view) {

Entity entity=new Entity(id,name,age,score);

getEntityDao().update(entity);

cursor.requery();

}

/**

*根据name查询*/

public void query(View view) {

if(!TextUtils.isEmpty(name)) {

// Query类代表了一个可以被重复执行的查询

Query<Entity>query=getEntityDao().queryBuilder()

.where(EntityDao.Properties.Name.eq(name))

.orderAsc(EntityDao.Properties.Id)

.build();

//查询结果以List返回List

count=query.list();

Toast.makeText(MainActivity.this,count.size()+"条数据被查到",Toast.LENGTH_SHORT).show();

}else{

Toast.makeText(MainActivity.this,"name不能为空",Toast.LENGTH_SHORT).show();

}

}

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容