Android 操作数据库的框架——greenDAO的学习

来源:互联网 发布:淘宝助手安卓版 编辑:程序博客网 时间:2024/05/16 06:20

转自: http://www.2cto.com/kf/201604/498026.html 作者没提供具体demo,所以写了一个供大家一块学习


demo下载地址:  点击打开下载链接


greenDAO的使用


简介

官网给出如下介绍:

\
greenDAO是一个对象关系映射(ORM)的框架,能够提供一个接口通过操作对象的方式去操作关系型数据库,它能够让你操作数据库时更简单、更方便。


在使用greenDAO的时候需要创建两个project,其中一个是java工程,它用来生成特定于您的项目的代码域(即生成了bean对象和操作数据库的dao)

核心的classes

\

DaoMaster:
DaoMaster保存了数据库对象和管理DAO类的classes,其提供了一些静态方法创建和删除表,内部类OpenHelper和DevOpenHelper 实现了SQLiteOpenHelper并创建数据库的框架。

DaoSession:
管理所有可用的DAO对象,可以通过getter方法获得。DaoSession还提供了一些通用的持久性方法比如插入、加载、更新,刷新和删除实体。

DAOs:
数据访问对象,每一个实体类都有对应的greenDAO对象。

Entities:
实体类对象

<h3 id="核心greendao类初始化数据库">核心greenDAO类初始化数据库
?
1
2
3
4
5
6
<code>helper = newDaoMaster.DevOpenHelper(this,"notes-db",null);
db = helper.getWritableDatabase();
daoMaster = newDaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();
</code>

主要优点

greenDAO 性能远远高于同类的 ORMLite,具体测试结果可见官网 greenDAO 支持 protocol buffer(protobuf) 协议数据的直接存储,如果你通过 protobuf 协议与服务器交互,将不需要任何的映射。 与 ORMLite 等使用注解方式的 ORM 框架不同,greenDAO 使用「Code generation」的方式,这也是其性能能大幅提升的原因。

使用方法

1.新建Android project并在main目录下新建文件夹java-gen(存放自动生成bean和dao)

2.在build.gradle中配置

?
1
2
3
4
5
6
7
8
9
10
<code>//buildTypes{}中配置
sourceSets {
    main {
        java.srcDirs = ['src/main/java','src/main/java-gen']
    }
}
 
//dependencies{}中配置
compile'de.greenrobot:greendao:2.1.0'
</code>

\

3.新建java project——greenDAO_java

在build.gradle中添加

?
1
2
<code>compile'de.greenrobot:greendao-generator:2.1.0'
</code>

创建模式对象,并添加实体(表)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<code>publicclassGenerator {
    publicstaticvoid main(String[] args) throwsException {
 
        intversion=1;
        String defaultPackage="test.greenDAO.bean";
        //创建模式对象,指定版本号和自动生成的bean对象的包名
        Schema schema=newSchema(version,defaultPackage);
        //指定自动生成的dao对象的包名,不指定则都DAO类生成在"test.greenDAO.bean"包中
        schema.setDefaultJavaPackageDao("test.greenDAO.dao");
 
        //添加实体
        addEntity(schema);
 
        String outDir="D:/adt-bundle-windows-x64/workspace/studio/frame/study_demo/testgreendao/src/main/java-gen";
        //调用DaoGenerator().generateAll方法自动生成代码到之前创建的java-gen目录下
        newDaoGenerator().generateAll(schema,outDir);
 
    }
 
    privatestaticvoid 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类型的age
        entity.addDoubleProperty("score");//添加Double的score
    }
}
</code>

4.运行java代码,自动在Android project的java-gen目录下生成bean类和DAO类

\

5.新建MyApplication继承Application,并在Manifest文件中配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<code>publicclassMyApplication extendsApplication{
 
    publicDaoSession daoSession;
    publicSQLiteDatabase db;
    publicDaoMaster.DevOpenHelper helper;
    publicDaoMaster daoMaster;
 
    @Override
    publicvoidonCreate() {
        super.onCreate();
        setupDatabase();
    }
 
    privatevoidsetupDatabase() {
        //创建数据库
        // 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
        // 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
        helper = newDaoMaster.DevOpenHelper(this,"test",null);
        //得到数据库连接对象
        db = helper.getWritableDatabase();
        //得到数据库管理者
        daoMaster =newDaoMaster(db);
        //得到daoSession,可以执行增删改查操作
        daoSession = daoMaster.newSession();
    }
 
    publicDaoSession getDaoSession() {
        returndaoSession;
    }
 
    publicSQLiteDatabase getDb() {
        returndb;
    }
 
}
</code>

6.编写MainActivity中的代码,实现用greenDAO进行数据库的操作

布局文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<code><!--?xml version="1.0"encoding="utf-8"?-->
<linearlayout android:layout_height="match_parent"android:layout_width="match_parent"android:orientation="vertical"xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools">
 
    <linearlayout android:layout_height="wrap_content"android:layout_marginleft="5dp"android:layout_marginright="5dp"android:layout_margintop="10dp"android:layout_width="match_parent"android:orientation="horizontal">
 
        <textview android:id="@+id/tv_id"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp"android:text="id:0">
 
        <edittext android:hint="name"android:id="@+id/et_name"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp">
 
        <edittext android:hint="age"android:id="@+id/et_age"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp">
 
        <edittext android:hint="score"android:id="@+id/et_score"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp">
    </edittext></edittext></edittext></textview></linearlayout>
 
    <linearlayout android:layout_height="wrap_content"android:layout_width="match_parent"android:orientation="horizontal"><button android:id="@+id/btn_add"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp"android:text="add"></button><button android:id="@+id/btn_delete"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp"android:text="delete"></button><button android:id="@+id/btn_update"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp"android:text="update"></button></linearlayout></linearlayout></code><button android:id="@+id/btn_query"android:layout_height="wrap_content"android:layout_margin="5dp"android:layout_weight="1"android:layout_width="0dp"android:text="query"><code>
     
 
    <listview android:id="@+id/lv_list"android:layout_height="match_parent"android:layout_width="match_parent">
 
</listview></code></button>

初始化视图

?
1
2
3
4
5
6
7
8
9
10
<code>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);
btn_add = (Button) findViewById(R.id.btn_add);
btn_delete = (Button) findViewById(R.id.btn_delete);
btn_update = (Button) findViewById(R.id.btn_update);
btn_query = (Button) findViewById(R.id.btn_query);
lv_list = (ListView) findViewById(R.id.lv_list);
</code>

得到cursor对象

?
1
2
3
4
5
<code>String orderBy = EntityDao.Properties.Id.columnName + " DESC";//根据Id降序排序
 
//查询,得到cursor
cursor = getDb().query(getEntityDao().getTablename(), getEntityDao().getAllColumns(), null,null,null,null, orderBy);
</code>

设置监听

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<code>btn_add.setOnClickListener(this);
btn_delete.setOnClickListener(this);
btn_update.setOnClickListener(this);
btn_query.setOnClickListener(this);
 
adapter = newMyAdapter(this, cursor);
lv_list.setAdapter(adapter);
lv_list.setOnItemClickListener(newAdapterView.OnItemClickListener() {
    @Override
    publicvoidonItemClick(AdapterView<!--?--> parent, View view, 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) + "");
    }
});
</code>

自定义CursorAdapter

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<code>classMyAdapterextendsCursorAdapter {
 
 
    publicMyAdapter(Context context, Cursor cursor) {
        super(context, cursor);
    }
 
    @Override
    publicView newView(Context context, Cursor cursor, ViewGroup parent) {
        ViewHolder holder = newViewHolder();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_db, parent, false);
        holder.tv_id = (TextView) view.findViewById(R.id.tv_id);
        holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
        holder.tv_age = (TextView) view.findViewById(R.id.tv_age);
        holder.tv_score = (TextView) view.findViewById(R.id.tv_score);
        view.setTag(holder);
        returnview;
    }
 
    @Override
    publicvoidbindView(View view, Context context, Cursor cursor) {
        ViewHolder holder = (ViewHolder) view.getTag();
        longid = cursor.getLong(0);
        String name = cursor.getString(1);
        intage = cursor.getInt(2);
        doublescore = cursor.getDouble(3);
        holder.tv_id.setText(id + "");
        holder.tv_name.setText(name);
        holder.tv_age.setText(age + "");
        holder.tv_score.setText(score + "");
    }
}
 
staticclassViewHolder {
    TextView tv_id;
    TextView tv_name;
    TextView tv_age;
    TextView tv_score;
}
</code>

数据库操作:增删改查的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<code>/**
 * 添加
 */
privatevoidaddEntity() {
    if(!TextUtils.isEmpty(name)) {
        Entity entity = newEntity(null, name, age, score);
        //面向对象添加表数据
        getEntityDao().insert(entity);
        cursor.requery();//刷新
    }else{
        Toast.makeText(MainActivity.this,"name不能为空", Toast.LENGTH_SHORT).show();
    }
}
 
/**
 * 根据id删除
 *
 * @param id
 */
privatevoiddeleteEntity(longid) {
    getEntityDao().deleteByKey(id);
    cursor.requery();
}
 
/**
 * 更新
 */
privatevoidupdateList() {
    Entity entity = newEntity(id, name, age, score);
    getEntityDao().update(entity);
    cursor.requery();
}
 
/**
 * 根据name查询
 *
 * @param name
 */
privatevoidquery(String name) {
    if(!TextUtils.isEmpty(this.name)) {
        // Query 类代表了一个可以被重复执行的查询
        Query<entity> query = getEntityDao().queryBuilder()
                .where(EntityDao.Properties.Name.eq(this.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();
    }
}
</entity></code>

demo演示:
\

 


1 0
原创粉丝点击