您的位置:首页 > 移动开发 > Android开发

Android框架 -- GreenDao

2015-12-17 20:33 459 查看
    开发过程中,总是将数据缓存在本地,不时的就使用到了数据库SQLite,编写SQL语句与解析结果等总是重复,烦躁的不行。听朋友说,适用于 Android 的ORM 框架很多,并对GreenDao推崇倍加,我也尝试这款框架。下面根据自己在Android Studio使用GreenDaode 经验,结合代码写下自己的总结:
 一、关于GreenDao



GreenDAO 是一个将对象映射到SQLite 数据库中的轻量且快速的 ORM 解决方案。(greenDAOis a light & fast ORM solution that maps objects to SQLite databases.).具体GreenDao基础,概念请查看light_sky翻译的官方文档。

二、   核心类解析
1 DaoMaster
保存了我们的SQLiteDataBase对象及操作DAO类。还有提供一些创建和删除Table的静态方法CreateAllTables/dropAllTables,它的内部类OpenHelper和DevOpenHelper实现了SQLiteOpenHelper并创建数据库的框架。
2.DaoSession
管理Dao对象,并通过getXXDao()获取。DaoSesion还封装了对实体Entity增删改查的方法。
3.xxDao
数据访问对象,对数据插入、更新、查询和删除。对于每一个实体,GreenDao都会生成一一对应的xxDao。
4.Property
对实体的属性限制。

1. 新建GreenDaoGenerator模块,GreenDaoGenerator仅仅是一个JAVA工程类。此模块决定GreenDao
Generator输出。以在这个类中通过对象、关系等创建数据库结构

</pre><pre name="code" class="java"><span style="font-size:18px;">public class GreenDaoGenerator {
public static void main(String[] args) throws Exception {
// 用于添加实体(Entity)的模式(Schema)对象。
// 参数1:数据库版本号:;参数2:自动生成代码的包路径。
Schema schema = new Schema(1, "com.teaphy.greendao");
//  分别指定生成的 Bean 与 DAO 类所在的目录
Schema schemaBean = new Schema(1, "com.teaphy.bean");
schema.setDefaultJavaPackageDao("com.teaphy.dao");

// 分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
// schema2.enableActiveEntitiesByDefault();
// schema2.enableKeepSectionsByDefault();

// Schema 对象使添加实体(Entities)
// 创建表Stu
addStu(schema);

// 使用 DAOGenerator 类的 generateAll() 方法自动生成代码
// 参数2为输出目录更改输出目录(既之前创建的 java-gen)。

new DaoGenerator().generateAll(schema, "/F:/AsWorkspace/GreenDaoDemo/app/src/main/java-gen");
}

// 添加实体Stu
private static void addStu(Schema schema) {
Entity entity = schema.addEntity("Stu");
// 设置属性 ID为主键、自增长
entity.addIdProperty().primaryKey().autoincrement();
entity.addStringProperty("name").notNull();
entity.addIntProperty("age");

}
}
</span>

  运行GreenDaoGenerator,如果运行正常,会在DaoMaster、DaoSession、StuDao三个类



2.在Android工程中对数据库进行操作

官方推荐将DaoMaster
和 DaoSession在Application里面初始化,防止多次创建Session.

public class MyApplication extends Application {

private static MyApplication mInstance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;

public void onCreate() {
super.onCreate();
if (mInstance == null)
mInstance = this;

}

/**
*  获取 DaoMaster
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {

if (null == daoMaster) {
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, Constants.DB_NAME, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}

return daoMaster;
}

/**
* 取得DaoSession
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}

}


在Activity里面处理增删改查:

@EActivity
public class MainActivity extends AppCompatActivity {

@ViewById
Button btn_add;
@ViewById
Button btn_delete;
@ViewById
Button btn_update;
@ViewById
Button btn_query;
@ViewById
ListView lv_data;
@ViewById
EditText edit_name;
@ViewById
EditText edit_age;

DaoMaster mDaoMaster;
DaoSession mDaoSession;
MyApplication mMyApplication;

StuDao stuDao;
SimpleAdapter simpleAdapter;

List<Map<String, Object>> listsStu;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyApplication = (MyApplication) getApplication();

mDaoMaster = MyApplication.getDaoMaster(this);
mDaoSession = MyApplication.getDaoSession(this);

stuDao = mDaoSession.getStuDao();

listsStu = new ArrayList<>();

}

@Override
protected void onResume() {
super.onResume();
simpleAdapter = new SimpleAdapter(
this,
listsStu,
R.layout.item_simple,
new String[]{"id", "name", "age"},
new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age});
lv_data.setAdapter(simpleAdapter);

}

@Click(R.id.btn_add)
void doAdd() {

stuDao.insert(new Stu(edit_name.getText().toString(),
Integer.parseInt(edit_age.getText().toString())));

edit_name.setText(null);
edit_age.setText(null);
}

@Click(R.id.btn_delete)
void doDelete() {
stuDao.delete(new Stu((long)3));
}

@Click(R.id.btn_update)
void doUpdate() {
stuDao.update(new Stu((long)1,"乌尔", 46));

}

@Click(R.id.btn_query)
void doQuery() {
List<Stu> lists = stuDao.queryBuilder().build().list();

Map<String, Object> maps;
listsStu.clear();

Log.i("123", "doQuery()");

for (Stu stu : lists) {
maps = new HashMap<>();
maps.put("id", stu.getId());
maps.put("name", stu.getName());
maps.put("age", stu.getAge());
listsStu.add(maps);
}

simpleAdapter.notifyDataSetChanged();

}

}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.greendaodemo.MainActivity">

<EditText
android:id="@+id/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入名字"/>
<EditText
android:id="@+id/edit_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入年龄"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="增"
android:background="@color/colorAccent"/>

<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删"
android:background="@color/colorPrimary"/>

<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="改"
android:background="@color/colorAccent"/>

<Button
android:id="@+id/btn_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查"
android:background="@color/colorPrimary"/>

</LinearLayout>

<ListView
android:id="@+id/lv_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">

</ListView>

</LinearLayout>
运行效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: