Android ORM 框架之 greenDAO

来源:互联网 发布:可以写作的软件 编辑:程序博客网 时间:2024/05/22 00:01

From:http://blog.csdn.net/kpioneer123/article/details/51354436

GreenDao是一个用于Android开发的对象/关系映射(ORM)工具。它向SQLite数据库提供了一个对象导向的接口。像GreenDao这样的ORM工具不仅为你省去了很多的重复工作,而且提供了更简便的操作接口。

greenDAO 代码生成的工程结构图




GREENDAO 设计的主要目标

  • 一个精简的库

  • 性能最大化

  • 内存开销最小化

  • 易于使用的 APIs

  • 对 Android 进行高度优化

GREENDAO 设计的主要特点

  • greenDAO 性能远远高于同类的 ORMLite。

  • greenDAO 支持 protocol buffer(protobuf) 协议数据的直接存储,如果你通过 protobuf 协议与服务器交互,将不需要任何的映射。

  • 与 ORMLite 等使用注解方式的 ORM 框架不同,greenDAO 使用「Code generation」的方式,这也是其性能能大幅提升的原因。

DAO CODE GENERATION PROJECT

这是其核心概念:为了在我们的 Android 工程中使用 greenDAO ,我们需要另建一个纯 Java Project,用于自动生成后继 Android 工程中需要使用到的 Bean、DAO、DaoMaster、DaoSession 等类。

为了在你的Android项目中使用GreenDao,你需要创建一个二级工程:“generator project”,它的任务就是为你的domain生成具体的代码。这个生成器工程就是一个普通的java工程。确保greenDao 的greenDao-generator.jar和 freemarker.jar 在classpath中。创建一个可执行的java类,构建你的实体模型并触发代码生成器,更多细节,可以参看 modelling文档。

核心类

一旦生成了指定的代码,就可以在你的android工程中使用greenDao了。别忘记在你的android工程中引入greenDao的核心jar包:greenDao.jar。以下是GreenDao的一些必要接口。


DaoMaster:

daomaster以一定的模式持有数据库对象(SQLiteDatabase)并管理一些DAO类(而不是对象)。

有一个静态的方法创建和drop数据库表。它的内部类OpenHelper和DevOpenHelper是SQLiteOpenHelper的实现类,用于创建SQLite数据库的模式。


DaoSession:

管理指定模式下所有可用的DAO对象,你可以通过某个get方法获取到。DaoSession提供一些通用的持久化方法,比如对实体进行插入,加载,更新,刷新和删除。最后DaoSession对象会跟踪identity scope,更多细节,可以参看 session文档。


DAOs(Data access objects):

数据访问对象,用于实体的持久化和查询。对于每一个实体,greenDao会生成一个DAO,相对于DaoSession它拥有更多持久化的方法,比如:加载全部,插入(insertInTx,语境不明了,暂且简单的翻译成插入)。


具体操作步骤:

Step1:在 ANDROID 工程中配置「GREENDAO GENERATOR」模块

1.在 .src/main 目录下新建一个与 java 同层级的「java-gen」目录,用于存放由 greenDAO 生成的 Bean、DAO、DaoMaster、DaoSession 等类。

   new->Directory  (mingjava-gen)


2.配置 Android 工程(app)的 build.gradle,在android{}结构体中分别添加 sourceSets 与dependencies。 



[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. sourceSets {  
  2.        main {  
  3.            java.srcDirs = ['src/main/java''src/main/java-gen']  
  4.        }  
  5.    }  
  6.   
  7. compile 'org.greenrobot:greendao:2.2.0'  

Step2:新建「GREENDAO GENERATOR」模块 (纯 JAVA 工程)
1.通过 File -> New -> New Module -> Java Library -> 填写相应的包名与类名 -> Finish.


通过这种方式生成的Module结构(我起名为greendao_generator )与一般情况不同

2.配置greendao_generator 工程的 build.gradle,添加 dependencies.
[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. compile 'org.greenrobot:greendao-generator:2.2.0'  

3.编写 MyClass类,注意: 我们的 Java 工程只有一个类,它的内容决定了「GreenDao Generator」的输出,你可以在这个类中通过对象、关系等创建数据库结构,下面我将以注释的形式详细讲解代码内容。
[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. package com.example;  
  2.   
  3. import de.greenrobot.daogenerator.DaoGenerator;  
  4. import de.greenrobot.daogenerator.Entity;  
  5. import de.greenrobot.daogenerator.Schema;  
  6.   
  7. public class MyClass{  
  8.   
  9.     public static void main(String[] args) throws Exception {  
  10.         // 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。  
  11.         // 两个参数分别代表:数据库版本号与自动生成代码的包路径。  
  12.         Schema schema = new Schema(1"com.xionghu.greendao");  
  13. //      当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:  
  14. //      Schema schema = new Schema(1, "me.itangqi.bean");  
  15. //      schema.setDefaultJavaPackageDao("me.itangqi.dao");  
  16.   
  17.         // 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。  
  18.         // schema2.enableActiveEntitiesByDefault();  
  19.         // schema2.enableKeepSectionsByDefault();  
  20.   
  21.         // 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。  
  22.         addNote(schema);  
  23.   
  24.         // 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录(既之前创建的 java-gen)。  
  25.         // 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。  
  26.         new DaoGenerator().generateAll(schema, "D:\\android_studio_4_6\\MyGreenDAO\\app\\src\\main\\java-gen");  
  27.     }  
  28.   
  29.     /** 
  30.      * @param schema 
  31.      */  
  32.     private static void addNote(Schema schema) {  
  33.         // 一个实体(类)就关联到数据库中的一张表,此处表名为「Note」(既类名)  
  34.         Entity note = schema.addEntity("Note");  
  35.         // 你也可以重新给表命名  
  36.         // note.setTableName("NODE");  
  37.   
  38.         // greenDAO 会自动根据实体类的属性值来创建表字段,并赋予默认值  
  39.         // 接下来你便可以设置表中的字段:  
  40.         note.addIdProperty();  
  41.         note.addStringProperty("text").notNull();  
  42.         // 与在 Java 中使用驼峰命名法不同,默认数据库中的命名是使用大写和下划线来分割单词的。  
  43.         // For example, a property called “creationDate” will become a database column “CREATION_DATE”.  
  44.         note.addStringProperty("comment");  
  45.         note.addDateProperty("date");  
  46.     }  
  47.   
  48. }  

Step3:

生成 DAO 文件(数据库)

执行 generator 工程,如一切正常,你将会在控制台看到如下日志,并且在主工程「java-gen」下会发现生成了DaoMaster、DaoSession、NoteDao、Note共4个类文件。
在这里需要对运行条件进行配置Android Studio 运行java程序






如图 再点run ,生成以下程序




运行时的输出框的正确信息


Step4:在 ANDROID 工程中进行数据库操作
[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. package com.cloudhome.mygreendao;  
  2.   
  3. import android.app.ListActivity;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.EditText;  
  10. import android.widget.ListView;  
  11. import android.widget.SimpleCursorAdapter;  
  12.   
  13. import com.xionghu.greendao.Note;  
  14. import com.xionghu.greendao.NoteDao;  
  15.   
  16. import java.text.DateFormat;  
  17. import java.util.Date;  
  18. import java.util.List;  
  19. import de.greenrobot.dao.query.Query;  
  20. import de.greenrobot.dao.query.QueryBuilder;  
  21.   
  22.   
  23.   
  24. public class MainActivity extends ListActivity {  
  25.     private EditText editText;  
  26.     private Cursor cursor;  
  27.     public static final String TAG = "DaoExample";  
  28.     private String orderBy;  
  29.     private String textColumn;  
  30.     private   SimpleCursorAdapter adapter;  
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.activity_main);  
  35.   
  36.         textColumn = NoteDao.Properties.Text.columnName;  
  37.   
  38.         orderBy=textColumn+" COLLATE LOCALIZED ASC";  
  39.   
  40.         cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), nullnullnullnull, orderBy);  
  41.   
  42.   
  43.         String[] from = {textColumn, NoteDao.Properties.Comment.columnName};  
  44.   
  45.         int[] to = {android.R.id.text1, android.R.id.text2};  
  46.   
  47.   
  48.         adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,  
  49.                 to);  
  50.   
  51.         setListAdapter(adapter);  
  52.   
  53.         adapter.notifyDataSetChanged();  
  54.   
  55.   
  56.         editText = (EditText) findViewById(R.id.editTextNote);  
  57.     }  
  58.   
  59.     private NoteDao getNoteDao() {  
  60.         // 通过 BaseApplication 类提供的 getDaoSession() 获取具体 Dao  
  61.         return ((BaseApplication) this.getApplicationContext()).getDaoSession().getNoteDao();  
  62.     }  
  63.   
  64.     private SQLiteDatabase getDb() {  
  65.         // 通过 BaseApplication 类提供的 getDb() 获取具体 db  
  66.         return ((BaseApplication) this.getApplicationContext()).getDb();  
  67.     }  
  68.   
  69.     /** 
  70.      * Button 点击的监听事件 
  71.      * 
  72.      * @param view 
  73.      */  
  74.     public void onMyButtonClick(View view) {  
  75.         switch (view.getId()) {  
  76.             case R.id.buttonAdd:  
  77.                 addNote();  
  78.                 break;  
  79.             case R.id.buttonQuery:  
  80.                 search();  
  81.                 break;  
  82.             default:  
  83.                 ToastUtils.show(getApplicationContext(), "What's wrong ?");  
  84.                 break;  
  85.         }  
  86.     }  
  87.   
  88.     private void addNote() {  
  89.         String noteText = editText.getText().toString();  
  90.         editText.setText("");  
  91.   
  92.         final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);  
  93.         String comment = "Added on " + df.format(new Date());  
  94.   
  95.         if (noteText == null || noteText.equals("")) {  
  96.             ToastUtils.show(getApplicationContext(), "Please enter a note to add");  
  97.         } else {  
  98.             // 插入操作,简单到只要你创建一个 Java 对象  
  99.             Note note = new Note(null, noteText, comment, new Date());  
  100.             getNoteDao().insert(note);  
  101.             Log.d(TAG, "Inserted new note, ID: " + note.getId());  
  102.   
  103.   
  104.   
  105.             cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), nullnullnullnull, orderBy);  
  106.   
  107.             String[] from = {textColumn, NoteDao.Properties.Comment.columnName};  
  108.   
  109.             int[] to = {android.R.id.text1, android.R.id.text2};  
  110.   
  111.   
  112.             adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,  
  113.                     to);  
  114.   
  115.             setListAdapter(adapter);  
  116.   
  117.             adapter.notifyDataSetChanged();  
  118.   
  119.   
  120.         }  
  121.   
  122.     }  
  123.   
  124.     private void search() {  
  125.         String noteText = editText.getText().toString();  
  126.         editText.setText("");  
  127.         if (noteText == null || noteText.equals("")) {  
  128.             ToastUtils.show(getApplicationContext(), "Please enter a note to query");  
  129.         } else {  
  130.             // Query 类代表了一个可以被重复执行的查询  
  131.             Query query = getNoteDao().queryBuilder()  
  132.                     .where(NoteDao.Properties.Text.eq(noteText))  
  133.                     .orderAsc(NoteDao.Properties.Date)  
  134.                     .build();  
  135.             // 查询结果以 List 返回  
  136.             List notes = query.list();  
  137.             ToastUtils.show(getApplicationContext(), "There have " + notes.size() + " records");  
  138.         }  
  139.         // 在 QueryBuilder 类中内置两个 Flag 用于方便输出执行的 SQL 语句与传递参数的值  
  140.         QueryBuilder.LOG_SQL = true;  
  141.         QueryBuilder.LOG_VALUES = true;  
  142.     }  
  143.   
  144.     /** 
  145.      * ListView 的监听事件,用于删除一个 Item 
  146.      * 
  147.      * @param l 
  148.      * @param v 
  149.      * @param position 
  150.      * @param id 
  151.      */  
  152.     @Override  
  153.     protected void onListItemClick(ListView l, View v, int position, long id) {  
  154.   
  155.         // 删除操作,你可以通过「id」也可以一次性删除所有  
  156.   
  157.         getNoteDao().deleteByKey(id);  
  158.   
  159. //       getNoteDao().deleteAll();  
  160.   
  161.         ToastUtils.show(getApplicationContext(), "Deleted note, ID: " + id);  
  162.   
  163.         Log.d(TAG, "Deleted note, ID: " + id);  
  164.   
  165.         cursor = getDb().query(getNoteDao().getTablename(), getNoteDao().getAllColumns(), nullnullnullnull, orderBy);  
  166.   
  167.         String[] from = {textColumn, NoteDao.Properties.Comment.columnName};  
  168.   
  169.         int[] to = {android.R.id.text1, android.R.id.text2};  
  170.   
  171.   
  172.         adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from,  
  173.                 to);  
  174.   
  175.         setListAdapter(adapter);  
  176.   
  177.         adapter.notifyDataSetChanged();  
  178.   
  179.   
  180.     }  
  181.   
  182.   
  183. }  

Step5:运行结果





demo下载

参考资料:
http://www.2cto.com/kf/201604/498026.html
https://github.com/greenrobot/greenDAO
https://github.com/tangqi92/MyGreenDAO
http://www.w2bc.com/Article/20726
http://blog.csdn.net/h3c4lenovo/article/details/43566169
http://my.oschina.net/u/2444750/blog/614059
0 0
原创粉丝点击