轉自:http://blog.csdn.net/krislight/article/details/9391455
greenDaoMaster的學習研究 分類: 心得筆記 2013-07-20 16:59 603人閱讀 評論(11) 收藏 舉報 greenDao 最近一直在研究一個第三方的開源框架,greenDaoMaster是一個移動開發的ORM框架,由於網上一直查不到使用資料,所以自己摸索總結下用法。 首先需要新建一個JAVA項目用來自動生成文件。需要導入greendao-generator-1.3.0.jar和freemarker.jar到項目中 示例代碼如下: [java] view plaincopy /* * Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.greenrobot.daogenerator.gentest; import de.greenrobot.daogenerator.DaoGenerator; import de.greenrobot.daogenerator.Entity; import de.greenrobot.daogenerator.Property; import de.greenrobot.daogenerator.Schema; import de.greenrobot.daogenerator.ToMany; /** * Generates entities and DAOs for the example project DaoExample. * * Run it as a Java application (not Android). * * @author Markus */ public class ExampleDaoGenerator { public static void main(String[] args) throws Exception { Schema schema = new Schema(3, "de.greenrobot.daoexample"); addNote(schema); addCustomerOrder(schema); new DaoGenerator().generateAll(schema, "../DaoExample/src-gen"); } private static void addNote(Schema schema) { Entity note = schema.addEntity("Note"); note.addIdProperty(); note.addStringProperty("text").notNull(); note.addStringProperty("comment"); note.addDateProperty("date"); } private static void addCustomerOrder(Schema schema) { Entity customer = schema.addEntity("Customer"); customer.addIdProperty(); customer.addStringProperty("name").notNull(); Entity order = schema.addEntity("Order"); order.setTableName("ORDERS"); // "ORDER" is a reserved keyword order.addIdProperty(); Property orderDate = order.addDateProperty("date").getProperty(); Property customerId = order.addLongProperty("customerId").notNull().getProperty(); order.addToOne(customer, customerId); ToMany customerToOrders = customer.addToMany(order, customerId); customerToOrders.setName("orders"); customerToOrders.orderAsc(orderDate); } } 來分析這段代碼: [java] view plaincopy Schema schema = new Schema(3, "de.greenrobot.daoexample"); Schema對象接受2個參數,第一個參數是DB的版本號,通過更新版本號來更新數據庫。第二個參數是自動生成代碼的包路徑。包路徑系統自動生成 在來看這段代碼 [java] view plaincopy Entity note = schema.addEntity("Note"); note.addIdProperty(); note.addStringProperty("text").notNull(); note.addStringProperty("comment"); note.addDateProperty("date"); Entity表示一個實體可以對應成數據庫中的表 系統自動會以傳入的參數作為表的名字,這里表名就是NOTE 當然也可以自己設置表的名字,像這樣: [java] view plaincopy order.setTableName("ORDERS"); 接下來是一些字段參數設置。 如果想ID自動增長可以像這樣: [java] view plaincopy order.addIdProperty().autoincrement(); 再來看這一段: [java] view plaincopy 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 greenDAO Generator Copyright 2011-2013 Markus Junginger, greenrobot.de. Licensed under GPL V3. This program comes with ABSOLUTELY NO WARRANTY Processing schema version 3... Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\NoteDao.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\Note.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\CustomerDao.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\Customer.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\OrderDao.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\Order.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\DaoMaster.java Written D:\android workspace\Open Source\greenDAO-master\DaoExample\src-gen\de\greenrobot\daoexample\DaoSession.java Processed 3 entities in 7743ms 可以看到DaoMaster中封裝了SQLiteDatabase和SQLiteOpenHelper 來看看如何使用GreenDao實現CRUD 如下代碼實現插入一個Note對象: [java] view plaincopy DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null); db = helper.getWritableDatabase(); daoMaster = new DaoMaster(db); daoSession = daoMaster.newSession(); noteDao = daoSession.getNoteDao(); Note note = new Note(null, noteText, comment, new Date()); noteDao.insert(note); 代碼變得如此簡單。 官方推薦將取得DaoMaster對象的方法放到Application層這樣避免多次創建生成Session對象。 感覺這個框架和Web的Hibernate有異曲同工之妙。 這里列出自己實際開發中的代碼方便記憶: 首先是在Application層實現得到DaoMaster和DaoSession的方法: [java] view plaincopy public class BaseApplication extends Application { private static BaseApplication mInstance; private static DaoMaster daoMaster; private static DaoSession daoSession; @Override public void onCreate() { super.onCreate(); if(mInstance == null) mInstance = this; } /** * 取得DaoMaster * * @param context * @return */ public static DaoMaster getDaoMaster(Context context) { if (daoMaster == null) { 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; } } 然后寫一個Db工具類: [java] view plaincopy public class DbService { private static final String TAG = DbService.class.getSimpleName(); private static DbService instance; private static Context appContext; private DaoSession mDaoSession; private NoteDao noteDao; private DbService() { } public static DbService getInstance(Context context) { if (instance == null) { instance = new DbService(); if (appContext == null){ appContext = context.getApplicationContext(); } instance.mDaoSession = BaseApplication.getDaoSession(context); instance.noteDao = instance.mDaoSession.getNoteDao(); } return instance; } public Note loadNote(long id) { return noteDao.load(id); } public List<Note> loadAllNote(){ return noteDao.loadAll(); } /** * query list with where clause * ex: begin_date_time >= ? AND end_date_time <= ? * @param where where clause, include 'where' word * @param params query parameters * @return */ public List<Note> queryNote(String where, String... params){ return noteDao.queryRaw(where, params); } /** * insert or update note * @param note * @return insert or update note id */ public long saveNote(Note note){ return noteDao.insertOrReplace(note); } /** * insert or update noteList use transaction * @param list */ public void saveNoteLists(final List<Note> list){ if(list == null || list.isEmpty()){ return; } noteDao.getSession().runInTx(new Runnable() { @Override public void run() { for(int i=0; i<list.size(); i++){ Note note = list.get(i); noteDao.insertOrReplace(note); } } }); } /** * delete all note */ public void deleteAllNote(){ noteDao.deleteAll(); } /** * delete note by id * @param id */ public void deleteNote(long id){ noteDao.deleteByKey(id); Log.i(TAG, "delete"); } public void deleteNote(Note note){ noteDao.delete(note); } } DB常量: [java] view plaincopy public class Constants { public static final String DB_NAME = "note_db"; } Note實體類: [java] view plaincopy // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table note. */ public class Note { private Long id; /** Not-null value. */ private String title; /** Not-null value. */ private String content; private java.util.Date createDate; public Note() { } public Note(Long id) { this.id = id; } public Note(Long id, String title, String content, java.util.Date createDate) { this.id = id; this.title = title; this.content = content; this.createDate = createDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** Not-null value. */ public String getTitle() { return title; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setTitle(String title) { this.title = title; } /** Not-null value. */ public String getContent() { return content; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setContent(String content) { this.content = content; } public java.util.Date getCreateDate() { return createDate; } public void setCreateDate(java.util.Date createDate) { this.createDate = createDate; } }
