android greendaoMaster的应用

第三方的开源框架,greenDaoMaster是一个移动开发的ORM框架,由于网上一直查不到使用资料,所以自己摸索总结下用法。

首先需要新建一个JAVA项目用来自动生成文件。需要导入greendao-generator-1.3.0.jar和freemarker.jar到项目中

示例代码如下:

[java] view plaincopy
  1. /* 
  2.  * Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de) 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. package de.greenrobot.daogenerator.gentest;  
  17.   
  18. import de.greenrobot.daogenerator.DaoGenerator;  
  19. import de.greenrobot.daogenerator.Entity;  
  20. import de.greenrobot.daogenerator.Property;  
  21. import de.greenrobot.daogenerator.Schema;  
  22. import de.greenrobot.daogenerator.ToMany;  
  23.   
  24. /** 
  25.  * Generates entities and DAOs for the example project DaoExample. 
  26.  *  
  27.  * Run it as a Java application (not Android). 
  28.  *  
  29.  * @author Markus 
  30.  */  
  31. public class ExampleDaoGenerator {  
  32.   
  33.     public static void main(String[] args) throws Exception {  
  34.           
  35.         Schema schema = new Schema(3"de.greenrobot.daoexample");  
  36.   
  37.         addNote(schema);  
  38.         addCustomerOrder(schema);  
  39.   
  40.         new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");  
  41.     }  
  42.   
  43.     private static void addNote(Schema schema) {  
  44.         Entity note = schema.addEntity("Note");  
  45.         note.addIdProperty();  
  46.         note.addStringProperty("text").notNull();  
  47.         note.addStringProperty("comment");  
  48.         note.addDateProperty("date");  
  49.     }  
  50.   
  51.     private static void addCustomerOrder(Schema schema) {  
  52.         Entity customer = schema.addEntity("Customer");  
  53.         customer.addIdProperty();  
  54.         customer.addStringProperty("name").notNull();  
  55.   
  56.         Entity order = schema.addEntity("Order");  
  57.         order.setTableName("ORDERS"); // "ORDER" is a reserved keyword  
  58.         order.addIdProperty();  
  59.         Property orderDate = order.addDateProperty("date").getProperty();  
  60.         Property customerId = order.addLongProperty("customerId").notNull().getProperty();  
  61.         order.addToOne(customer, customerId);  
  62.   
  63.         ToMany customerToOrders = customer.addToMany(order, customerId);  
  64.         customerToOrders.setName("orders");  
  65.         customerToOrders.orderAsc(orderDate);  
  66.     }  
  67.   
  68. }  
来分析这段代码:

[java] view plaincopy
  1. Schema schema = new Schema(3"de.greenrobot.daoexample");  

Schema对象接受2个参数,第一个参数是DB的版本号,通过更新版本号来更新数据库。第二个参数是自动生成代码的包路径。包路径系统自动生成

在来看这段代码

[java] view plaincopy
  1. Entity note = schema.addEntity("Note");  
  2.         note.addIdProperty();  
  3.         note.addStringProperty("text").notNull();  
  4.         note.addStringProperty("comment");  
  5.         note.addDateProperty("date");  

Entity表示一个实体可以对应成数据库中的表

系统自动会以传入的参数作为表的名字,这里表名就是NOTE

当然也可以自己设置表的名字,像这样:

[java] view plaincopy
  1. order.setTableName("ORDERS");  

接下来是一些字段参数设置。

如果想ID自动增长可以像这样:

[java] view plaincopy
  1. order.addIdProperty().autoincrement();  

再来看这一段:

[java] view plaincopy
  1. new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");  

第一个参数是Schema对象,第二个参数是希望自动生成的代码对应的项目路径。

试了下src-gen这个文件夹必须手动创建,这里路径如果错了会抛出异常。

好了先别慌运行这段程序。新建一个Android项目名字是DaoExample,和刚才的JAVA项目保持在同一个文件夹下。

接着就可以运行刚才的JAVA程序,会看到src-gen下面自动生成了8个文件,3个实体对象,3个dao,1个DaoMaster,

1个DaoSession

[java] view plaincopy
  1. greenDAO Generator  
  2. Copyright 2011-2013 Markus Junginger, greenrobot.de. Licensed under GPL V3.  
  3. This program comes with ABSOLUTELY NO WARRANTY  
  4. Processing schema version 3...  
  5. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleNoteDao.java  
  6. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleNote.java  
  7. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleCustomerDao.java  
  8. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleCustomer.java  
  9. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleOrderDao.java  
  10. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleOrder.java  
  11. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleDaoMaster.java  
  12. Written D:android workspaceOpen SourcegreenDAO-masterDaoExamplesrc-gendegreenrobotdaoexampleDaoSession.java  
  13. Processed 3 entities in 7743ms  

可以看到DaoMaster中封装了SQLiteDatabase和SQLiteOpenHelper

来看看如何使用GreenDao实现CRUD

如下代码实现插入一个Note对象:

[java] view plaincopy
  1. DevOpenHelper helper = new DaoMaster.DevOpenHelper(this"notes-db"null);  
  2.      db = helper.getWritableDatabase();  
  3.      daoMaster = new DaoMaster(db);  
  4.      daoSession = daoMaster.newSession();  
  5.      noteDao = daoSession.getNoteDao();  
  6.      Note note = new Note(null, noteText, comment, new Date());  
  7.      noteDao.insert(note);  
代码变得如此简单。

官方推荐将取得DaoMaster对象的方法放到Application层这样避免多次创建生成Session对象。

感觉这个框架和Web的Hibernate有异曲同工之妙。

这里列出自己实际开发中的代码方便记忆:

首先是在Application层实现得到DaoMaster和DaoSession的方法:

[java] view plaincopy
  1. public class BaseApplication extends Application {  
  2.       
  3.     private static BaseApplication mInstance;  
  4.     private static DaoMaster daoMaster;  
  5.     private static DaoSession daoSession;  
  6.       
  7.     @Override  
  8.     public void onCreate() {  
  9.         super.onCreate();  
  10.         if(mInstance == null)  
  11.             mInstance = this;  
  12.     }  
  13.       
  14.     /** 
  15.      * 取得DaoMaster 
  16.      *  
  17.      * @param context 
  18.      * @return 
  19.      */  
  20.     public static DaoMaster getDaoMaster(Context context) {  
  21.         if (daoMaster == null) {  
  22.             OpenHelper helper = new DaoMaster.DevOpenHelper(context,Constants.DB_NAME, null);  
  23.             daoMaster = new DaoMaster(helper.getWritableDatabase());  
  24.         }  
  25.         return daoMaster;  
  26.     }  
  27.       
  28.     /** 
  29.      * 取得DaoSession 
  30.      *  
  31.      * @param context 
  32.      * @return 
  33.      */  
  34.     public static DaoSession getDaoSession(Context context) {  
  35.         if (daoSession == null) {  
  36.             if (daoMaster == null) {  
  37.                 daoMaster = getDaoMaster(context);  
  38.             }  
  39.             daoSession = daoMaster.newSession();  
  40.         }  
  41.         return daoSession;  
  42.     }  
  43. }  

然后写一个Db工具类:

[java] view plaincopy
  1. public class DbService {  
  2.       
  3.     private static final String TAG = DbService.class.getSimpleName();  
  4.     private static DbService instance;  
  5.     private static Context appContext;  
  6.     private DaoSession mDaoSession;  
  7.     private NoteDao noteDao;  
  8.       
  9.       
  10.     private DbService() {  
  11.     }  
  12.   
  13.     public static DbService getInstance(Context context) {  
  14.         if (instance == null) {  
  15.             instance = new DbService();  
  16.             if (appContext == null){  
  17.                 appContext = context.getApplicationContext();  
  18.             }  
  19.             instance.mDaoSession = BaseApplication.getDaoSession(context);  
  20.             instance.noteDao = instance.mDaoSession.getNoteDao();  
  21.         }  
  22.         return instance;  
  23.     }  
  24.       
  25.       
  26.     public Note loadNote(long id) {  
  27.         return noteDao.load(id);  
  28.     }  
  29.       
  30.     public List<Note> loadAllNote(){  
  31.         return noteDao.loadAll();  
  32.     }  
  33.       
  34.     /** 
  35.      * query list with where clause 
  36.      * ex: begin_date_time >= ? AND end_date_time <= ? 
  37.      * @param where where clause, include 'where' word 
  38.      * @param params query parameters 
  39.      * @return 
  40.      */  
  41.       
  42.     public List<Note> queryNote(String where, String... params){  
  43.         return noteDao.queryRaw(where, params);  
  44.     }  
  45.       
  46.       
  47.     /** 
  48.      * insert or update note 
  49.      * @param note 
  50.      * @return insert or update note id 
  51.      */  
  52.     public long saveNote(Note note){  
  53.         return noteDao.insertOrReplace(note);  
  54.     }  
  55.       
  56.       
  57.     /** 
  58.      * insert or update noteList use transaction 
  59.      * @param list 
  60.      */  
  61.     public void saveNoteLists(final List<Note> list){  
  62.             if(list == null || list.isEmpty()){  
  63.                  return;  
  64.             }  
  65.             noteDao.getSession().runInTx(new Runnable() {  
  66.             @Override  
  67.             public void run() {  
  68.                 for(int i=0; i<list.size(); i++){  
  69.                     Note note = list.get(i);  
  70.                     noteDao.insertOrReplace(note);  
  71.                 }  
  72.             }  
  73.         });  
  74.           
  75.     }  
  76.       
  77.     /** 
  78.      * delete all note 
  79.      */  
  80.     public void deleteAllNote(){  
  81.         noteDao.deleteAll();  
  82.     }  
  83.       
  84.     /** 
  85.      * delete note by id 
  86.      * @param id 
  87.      */  
  88.     public void deleteNote(long id){  
  89.         noteDao.deleteByKey(id);  
  90.         Log.i(TAG, "delete");  
  91.     }  
  92.       
  93.     public void deleteNote(Note note){  
  94.         noteDao.delete(note);  
  95.     }  
  96.       
  97. }  

DB常量:

[java] view plaincopy
  1. public class Constants {  
  2.     public static final String DB_NAME = "note_db";  
  3. }  

Note实体类:

[java] view plaincopy
  1. // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.   
  2. /** 
  3.  * Entity mapped to table note. 
  4.  */  
  5. public class Note {  
  6.   
  7.     private Long id;  
  8.     /** Not-null value. */  
  9.     private String title;  
  10.     /** Not-null value. */  
  11.     private String content;  
  12.     private java.util.Date createDate;  
  13.   
  14.     public Note() {  
  15.     }  
  16.   
  17.     public Note(Long id) {  
  18.         this.id = id;  
  19.     }  
  20.   
  21.     public Note(Long id, String title, String content, java.util.Date createDate) {  
  22.         this.id = id;  
  23.         this.title = title;  
  24.         this.content = content;  
  25.         this.createDate = createDate;  
  26.     }  
  27.   
  28.     public Long getId() {  
  29.         return id;  
  30.     }  
  31.   
  32.     public void setId(Long id) {  
  33.         this.id = id;  
  34.     }  
  35.   
  36.     /** Not-null value. */  
  37.     public String getTitle() {  
  38.         return title;  
  39.     }  
  40.   
  41.     /** Not-null value; ensure this value is available before it is saved to the database. */  
  42.     public void setTitle(String title) {  
  43.         this.title = title;  
  44.     }  
  45.   
  46.     /** Not-null value. */  
  47.     public String getContent() {  
  48.         return content;  
  49.     }  
  50.   
  51.     /** Not-null value; ensure this value is available before it is saved to the database. */  
  52.     public void setContent(String content) {  
  53.         this.content = content;  
  54.     }  
  55.   
  56.     public java.util.Date getCreateDate() {  
  57.         return createDate;  
  58.     }  
  59.   
  60.     public void setCreateDate(java.util.Date createDate) {  
  61.         this.createDate = createDate;  
  62.     }  
  63.   
  64. }  
原文地址:https://www.cnblogs.com/lechance/p/4373215.html