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使用教程》

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倍。在一些特殊的应用中,加载速度是至关重要的。

《greenDAO使用教程》 (数据和图表更新于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;

《greenDAO使用教程》

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’

《greenDAO使用教程》

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文件夹下:

《greenDAO使用教程》
《greenDAO使用教程》

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;

}

}

《greenDAO使用教程》

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”>

《greenDAO使用教程》

(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();

}

}

}

《greenDAO使用教程》

    原文作者:sunny_zhang
    原文地址: https://www.jianshu.com/p/35616b5db364
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞