轉自:http://blog.csdn.net/krislight/article/details/9391455java
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; } }