GreenDao分析概括

来源:互联网 发布:淘宝首页psd模板教程 编辑:程序博客网 时间:2024/05/18 01:10

1.介绍

第一篇How to get started ? 原文地址:http://greendao-orm.com/documentation/how-to-get-started/该教程会带你浏览一个简单的greenDao示例工程。地址:https://github.com/greenrobot/greenDAO ,该工程包含两个子工程:DaoExample(android project)和DaoExampleGenerator(java project)。

你可以clone到本地,运行或者直接在github上直接浏览。

greenDao是一个开源的ORM(对象关系映射)框架,故名思议,他很好的封装了object(对象)与数据库(SQLiteOpenHelper & SQLiteDatabse)之间的关系

这里主要涉及到四个类:DaoMaster.java,DaoSession.java,ObjectDao.java(这里的object可以是你抽象出来的任意对象),Object.java,很方便的是,这几个文件DaoGenerator都可以自动生成。其中,DaoMaster就是一个数据库的角色,DaoSession的数据库对话的角色,ObjectDao是表的角色,Object则是表中的数据的角色这样分析以后,通常是一个路径下,DaoGenerator生成了多个ObjectDao和Object文件,但是只有一个DaoMaster和DaoSession文件,就是一个数据库对应了多张表的结构。

对应生成的文件


2.分析

1).数据——Object,基本属性,setter & getter


2).表——objectDao,主要封装了对表的操作的接口,(创建,增删改查 and so on)



3.对话——DaoSession,一些配置信息,和要注册的内容



4.数据库——DaoMaster,自身数据库的初始化,以及Daosession实例的获取



3.实例

public class NoteActivity extends ListActivity {    private SQLiteDatabase db;    private EditText editText;    private DaoMaster daoMaster;    private DaoSession daoSession;    private NoteDao noteDao;    private Cursor cursor;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);        db = helper.getWritableDatabase(); //独立创建        daoMaster = new DaoMaster(db);        daoSession = daoMaster.newSession();        noteDao = daoSession.getNoteDao();        String textColumn = NoteDao.Properties.Text.columnName;        String orderBy = textColumn + " COLLATE LOCALIZED ASC";        cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(), null, null, null, null, orderBy);        String[] from = { textColumn, NoteDao.Properties.Comment.columnName };        int[] to = { android.R.id.text1, android.R.id.text2 };        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,                to);        setListAdapter(adapter);        editText = (EditText) findViewById(R.id.editTextNote);        addUiListeners();    }}


0 0
原创粉丝点击