配置使用Android數據庫開源框架GreenDao

xg48 9年前發布 | 161K 次閱讀 Android開發 移動開發 greenDAO

GreenDao介紹

android開發的本地數據庫存儲是sqlite。greenDAO應該算是當前最火的數據庫開源框架了吧,它是一個移動開發的ORM(object / relational mapping)框架,是對sqlite數據庫訪問的對象化封裝。以對象的形式去訪問數據庫,數據庫表里面的字段就相當于對象的屬性了。可以直接obj.data的形式訪問了。如果覺得效率不夠高,你也可以自己ORM的框架。據我所致GreeDao是android開發性能最好的數據庫開源框架。

GreenDao 圖解

總之,一句話,greenDAO就是實現Java對象和SQLiteDatebase的一個媒介人,簡化了SQLite的操作。接下來介紹使用過程。

一.下載GreenDao
要使用肯定要先下載他的軟件包了,官網上有它的連接,對于marven和gradle環境直接到serarch.maven.org上下載jar包就好了。
GreenDao下載截圖

下載的jar導入到工程里面就可以了,通常都是/libs目錄下。
我這里也提供一個csdn的下載地址:http://download.csdn.net/detail/csm_qz/8569031

上面那個下載地址下載解壓后有三個文件如下圖



首先我們要創建java generator工程greendao-generator-1.3.0.jar 和 freemarker-2.3.20.jar是我們創建java generator工程時生成Dao文件需要用到的(什么是我說的Dao文件,往下看就會知道) 

greendao-1.3.7.jar是Android開發中需要用到的

二.創建generator工程(用來生成GreenDao開發過程中需要的java文件)
(1)創建Java工程(非Android工程) 
(2)導入greenDao-generator.jar和freemarker.jar兩個包。freemarker是一個用java寫的模板引擎,它能夠基于模板來生成文本輸出。應該就是用來自動生成DAO文件的。eclipse下面就是在properties –> Java build path –> libraries下面導入jar包。 
(3)創建一個包javagreendao 
(4)創建一個類,類名為ExampleDaoGenerator,類的定義如下:

package javagreendao;
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 { //總之main函數就執行了下面幾個函數
    public static void main(String[] args) throws Exception { // 參數3是數據庫版本號,“com.cn.speedchat.greendao”是包名,也就是說生成的Dao文件會在這個包下,可以將Schema理解為數據庫上下文吧
      Schema schema = new Schema(3, "com.cn.speedchat.greendao"); 
      //addNote() addSession() addReplay()這三個函數相當于建立了三個表,表名你都可以不用管了會自動生成
     addNote(schema);       
     addSession(schema);
     addReplay(schema);
     addCustomerOrder(schema);
    
    //這個是生成Dao文件的路徑的位置,這個代表當前工程的上一級目錄的javagreendao的src-gen文件夾里面,其實就是跟src同一級目錄,所以你自己要在src同一級目錄下新建一個src-gen文件夾待會要生成的文件
     new DaoGenerator().generateAll(schema, "../javagreendao/src-gen");    
    
    } //這個是一個Note表,然后后面的node.add***是表的字段名以及屬性
    private static void addNote(Schema schema)
    {
     //"MqttChatEntity"相當于是表的類名,用MqttChatEntity生成對象就可以訪問這個表屬性了,也就是這個表對應了這個類,待會使用你就會明白了
     Entity note = schema.addEntity("MqttChatEntity");    
     note.addIdProperty().autoincrement();
     note.addIntProperty("mode").notNull();
     note.addStringProperty("sessionid").notNull();
     note.addStringProperty("from").notNull();
     note.addStringProperty("to").notNull();
     note.addStringProperty("v_code");
     note.addStringProperty("timestamp").notNull();
     note.addStringProperty("platform");
     note.addStringProperty("message");
     note.addBooleanProperty("isread").notNull();
     note.addLongProperty("gossipid");
     note.addStringProperty("gossip");
     note.addIntProperty("chattype").notNull();
     note.addStringProperty("imagepath");
     note.addStringProperty("base64image");
    
    } //這個是一個Session表,然后后面的node.add***是表的字段名以及屬性(這是我寫的會話的一個表) private static void addSession(Schema schema)
    {
     Entity note = schema.addEntity("SessionEntity");
     note.addIdProperty().autoincrement();
     note.addStringProperty("sessionid").notNull().unique();
     note.addStringProperty("from").notNull();
     note.addStringProperty("to").notNull();
     note.addLongProperty("gossipid").notNull();
     note.addStringProperty("gossip");
     note.addIntProperty("sessiontype").notNull();
     note.addBooleanProperty("asdasd").notNull();
    
    } //這個是一個Replay表,然后后面的node.add***是表的字段名以及屬性(這是我寫的回復的一個表) private static void addReplay(Schema schema) {
     //ReplayEntity對應的類名
     Entity note = schema.addEntity("ReplayEntity");    
     note.addIdProperty().autoincrement();
     note.addIntProperty("mode").notNull();
     note.addStringProperty("from").notNull();
     note.addStringProperty("to").notNull();
     note.addStringProperty("v_code");
     note.addStringProperty("timestamp").notNull();
     note.addStringProperty("platform");
     note.addStringProperty("message");
     note.addIntProperty("msgtype").notNull();
     note.addBooleanProperty("isread").notNull();
    
    } //這個不用管了,照抄吧 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);
}                                                                                                                                                                                                                                                                                                              

}</pre></h2>

1)增加表如果你自己想加一些其他的表的話,你可以自己按照addSession,addNote ,addReplay三個函數的方式加,類名、字段名可以自己隨便取比如說,比我我要加一個用戶表,字段包括name,age,sex三個,我可以這樣做

    private static void addUser(Schema schema)  
    {
        Entity note = schema.addEntity("UserEntity");    
        note.addIdProperty().autoincrement();
        note.addStringProperty("name").notNull();
        note.addIntProperty("age").notNull();
        //true代表男,false代表女
        note.addBooleanProperty("sex").notNull();    
    } 


然后在main函數里面做如下調用


    public static void main(String[] args) throws Exception
    {
        Schema schema = new Schema(3, "com.cn.speedchat.greendao");    
        addNote(schema);        
        addSession(schema);
        addReplay(schema);
        addUser(schema);
        addCustomerOrder(schema);
        new DaoGenerator().generateAll(schema, "../javagreendao/src-gen");
    }

2)刪除表當然一些不需要的表你可以不用,刪掉就行,比如說你不須要addReplay,你就在main函數里面別調用addReplay(schema)就行


總之呢,這就是一個基于greenDao-generator.jar和freemarker.jar兩個包的java工程

然后運行該工程,控制臺打印出如下結果:

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 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/MqttChatEntityDao.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/MqttChatEntity.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/SessionEntityDao.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/SessionEntity.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/ReplayEntityDao.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/ReplayEntity.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/CustomerDao.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/Customer.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/OrderDao.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/Order.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/DaoMaster.java 
Written 
/home/csm/workspace/javagreendao/src-gen/com/cn/speedchat/greendao/DaoSession.java 
Processed 5 entities in 189ms

這代表成功的生成了Dao文件,然后我們按F5刷新該工程,在查看src-gen目錄文件,自動生成了很多java文件,這就是我們要的,我這里截圖給大家看


但是有很多錯誤是不是,沒關系,這個工程識別不了這些文件,這些文件是基于greendao-1.3.7.jar包的,是Android工程里面要用到的。先不管這個java工程了。接下來往下走

三.創建Android工程
(1)創建一個Android工程


(2)導入greendao-1.3.7.jar 方法是將greendao-1.3.7.jar文件放在libs文件夾下,然后右鍵該jar包=>add to build path

(3)將上面java工程生成的包”com.cn.speedchat.greendao”復制到該工程下面來,沒有報錯了,所以說在該Android工程下可以使用GreenDao了



我們拿一個文件來分析,比如MqttChatEntity.java文件,內容如下:

</span>
package com.cn.speedchat.greendao;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/* Entity mapped to table SESSION_ENTITY. */ public class SessionEntity {

private Long id;
/** Not-null value. */
private String sessionid;
/** Not-null value. */
private String from;
/** Not-null value. */
private String to;
private long gossipid;
private String gossip;
private int sessiontype;
private boolean asdasd;


public SessionEntity() {
}


public SessionEntity(Long id) {
    this.id = id;
}


public SessionEntity(Long id, String sessionid, String from, String to, long gossipid, String gossip, int sessiontype, boolean asdasd) {
    this.id = id;
    this.sessionid = sessionid;
    this.from = from;
    this.to = to;
    this.gossipid = gossipid;
    this.gossip = gossip;
    this.sessiontype = sessiontype;
    this.asdasd = asdasd;
}


public Long getId() {
    return id;
}


public void setId(Long id) {
    this.id = id;
}


/** Not-null value. */
public String getSessionid() {
    return sessionid;
}


/** Not-null value; ensure this value is available before it is saved to the database. */
public void setSessionid(String sessionid) {
    this.sessionid = sessionid;
}


/** Not-null value. */
public String getFrom() {
    return from;
}


/** Not-null value; ensure this value is available before it is saved to the database. */
public void setFrom(String from) {
    this.from = from;
}


/** Not-null value. */
public String getTo() {
    return to;
}


/** Not-null value; ensure this value is available before it is saved to the database. */
public void setTo(String to) {
    this.to = to;
}


public long getGossipid() {
    return gossipid;
}


public void setGossipid(long gossipid) {
    this.gossipid = gossipid;
}


public String getGossip() {
    return gossip;
}


public void setGossip(String gossip) {
    this.gossip = gossip;
}


public int getSessiontype() {
    return sessiontype;
}


public void setSessiontype(int sessiontype) {
    this.sessiontype = sessiontype;
}


public boolean getAsdasd() {
    return asdasd;
}


public void setAsdasd(boolean asdasd) {
    this.asdasd = asdasd;
} 

}</pre>
這就是我們平時寫Android封裝的一個普通的類,將一個表的字段封裝到一個類里面了,然后我們就可以以對象的形式去訪問,說白了就是數據庫里面的一條數據對應一個對象了,下面看看怎么使用

(4)官方推薦將取得DaoMaster對象的方法放到Application層這樣避免多次創建生成Session對象,在Application實現得到DaoMaster和DaoSession的方法,實現如下,新建一個ControlApp.java文件繼承自Application: </h2>

package com.cn.greendaotest;

import com.cn.speedchat.greendao.DaoMaster; import com.cn.speedchat.greendao.DaoMaster.OpenHelper; import com.cn.speedchat.greendao.DaoSession;

import android.app.Application; import android.content.Context; import android.database.sqlite.SQLiteDatabase;

public class ControlApp extends Application{

private static DaoMaster daoMaster;     
private static DaoSession daoSession;   
public static  SQLiteDatabase db;
//數據庫名,表名是自動被創建的    
public static final String DB_NAME = "dbname.db";    


public static DaoMaster getDaoMaster(Context context) {  
  if (daoMaster == null) {  
      OpenHelper helper = new DaoMaster.DevOpenHelper(context,DB_NAME, null);  
      daoMaster = new DaoMaster(helper.getWritableDatabase());  
  }  
  return daoMaster;     

}

 public static DaoSession getDaoSession(Context context) {  
  if (daoSession == null) {  
      if (daoMaster == null) {  
          daoMaster = getDaoMaster(context);  
      }  
      daoSession = daoMaster.newSession();  
  }  
  return daoSession;     

}

  public static SQLiteDatabase getSQLDatebase(Context context) {  
  if (daoSession == null) {  
      if (daoMaster == null) {  
          daoMaster = getDaoMaster(context);  
      }  
      db = daoMaster.getDatabase();  
  }  
      return db;     
  }  


@Override   
public void onCreate() {

}

}</pre>
(5)創建一個DBHelper的幫助類,這個幫助類寫了自己封裝的一些方法,內容如下 </h2>

package com.cn.speedchat.greendao;
import java.util.ArrayList;
import java.util.List;
import com.cn.greendaotest.ControlApp;
import com.cn.speedchat.greendao.MqttChatEntityDao.Properties;
import de.greenrobot.dao.query.QueryBuilder;
import android.content.Context;
import android.util.Log;

public class DBHelper { private static final String TAG = DBHelper.class.getSimpleName();
private static DBHelper instance;
private static Context appContext; private DaoSession mDaoSession;
private MqttChatEntityDao chatDao; private SessionEntityDao sessionDao;
private DBHelper() { } //單例模式,DBHelper只初始化一次 public static DBHelper getInstance(Context context) {
if (instance == null) { instance = new DBHelper();
if (appContext == null){
appContext = context.getApplicationContext();
}
instance.mDaoSession = ControlApp.getDaoSession(context); instance.chatDao = instance.mDaoSession.getMqttChatEntityDao(); instance.sessionDao = instance.mDaoSession.getSessionEntityDao(); } return instance;
}

//刪除Session表
public  void dropSessionTable()
{
    SessionEntityDao.dropTable(mDaoSession.getDatabase(), true);
}
//刪除MqttChatEntity表
public void dropChatTable()
{
    MqttChatEntityDao.dropTable(mDaoSession.getDatabase(), true);
}
//刪除所有表
public void dropAllTable()
{
    MqttChatEntityDao.dropTable(mDaoSession.getDatabase(), true);
    SessionEntityDao.dropTable(mDaoSession.getDatabase(), true);
 ReplayEntityDao.dropTable(mDaoSession.getDatabase(), true);
}
//創建所有表
public void createAllTable()
{
    MqttChatEntityDao.createTable(mDaoSession.getDatabase(), true);
    SessionEntityDao.createTable(mDaoSession.getDatabase(), true);
 ReplayEntityDao.createTable(mDaoSession.getDatabase(), true);
}
/** 
 * insert or update note 
 * @param note 
 * @return insert or update note id 
 */  
//插入或者刪除session項
public long saveSession(SessionEntity session){  
    return sessionDao.insertOrReplace(session);  
}  


//獲得所有的Session倒序排存到List列表里面
public List<SessionEntity> loadAllSession() {
    List<SessionEntity> sessions = new ArrayList<SessionEntity>();
    List<SessionEntity> tmpSessions = sessionDao.loadAll();
    int len = tmpSessions.size();
    for (int i = len-1; i >=0; i--) {
            sessions.add(tmpSessions.get(i));
    }
    return sessions;
}  


public void DeleteSession(SessionEntity entity) {
    sessionDao.delete(entity);
}  
//刪除某一項Session    
public void DeleteNoteBySession(SessionEntity entity) {
    QueryBuilder<MqttChatEntity> mqBuilder = chatDao.queryBuilder();
    mqBuilder.where(Properties.Sessionid.eq(entity.getSessionid()));
    List<MqttChatEntity> chatEntityList = mqBuilder.build().list();
    chatDao.deleteInTx(chatEntityList);
}  


//根據id找到某一項
public MqttChatEntity loadNote(long id) {
    return chatDao.load(id);  
}  
//獲得所有的MqttChatEntity列表 
public List<MqttChatEntity> loadAllNote(){  
    return chatDao.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 
 */  
  //查詢滿足params條件的列表
public List<MqttChatEntity> queryNote(String where, String... params){
    ArrayList<MqttChatEntity> ad = new ArrayList<MqttChatEntity>();
    return chatDao.queryRaw(where, params); 
}


//不一一介紹了,大家可以自己寫,有些比較難的查詢可以使用QueryBuilder來查詢
public List<MqttChatEntity> loadLastMsgBySessionid(String sessionid){
    QueryBuilder<MqttChatEntity> mqBuilder = chatDao.queryBuilder();
    mqBuilder.where(Properties.Sessionid.eq(sessionid))
    .orderDesc(Properties.Id)
    .limit(1);
    return mqBuilder.list();
}


public List<MqttChatEntity> loadMoreMsgById(String sessionid, Long id){
    QueryBuilder<MqttChatEntity> mqBuilder = chatDao.queryBuilder();
    mqBuilder.where(Properties.Id.lt(id))
    .where(Properties.Sessionid.eq(sessionid))
    .orderDesc(Properties.Id)
    .limit(20);
    return mqBuilder.list();
}


/** 
 * delete all note 
 */  
public void deleteAllNote(){  
    chatDao.deleteAll();  
}  


/** 
 * delete note by id 
 * @param id 
 */  
public void deleteNote(long id){  
    chatDao.deleteByKey(id);  
    Log.i(TAG, "delete");  
}  


public void deleteNote(MqttChatEntity note){  
    chatDao.delete(note);  
}  

}</pre>

</div>

四,使用
在Android工程下創建一個Activity使用如下(是一個啟動Activity ps:launcher):

package com.cn.greendaotest;
import java.util.List;
import com.cn.speedchat.greendao.DBHelper;
import com.cn.speedchat.greendao.SessionEntity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity { private DBHelper dBManager; //定義一個DBHelper對象,用他來對數據庫進行增刪改查

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    dBManager = DBHelper.getInstance(this);    //得到DBHelper對象
    SessionEntity entity = new SessionEntity();    //創建一個SessionEntity實體對象,并賦值
    entity.setFrom("A");
    entity.setGossip("大家好嗎?我來了...");
    entity.setGossipid(10);
    entity.setSessionid("abcdefg");
    entity.setSessiontype(1);
    entity.setTo("B");

//下面這一行就把entity對象存數據庫了,然后我們新建一個SessionEntity列表再讀一下 dBManager.saveSession(entity); //保存到數據庫

     //下面這個方法是查詢Session表里面的所有數據返回一個數據列表,相當于select * from table,然后掃描打印出來
    List<SessionEntity> listentity = dBManager.loadAllSession(); 


    for(int i=0;i<listentity.size();i++)
    {
        SessionEntity tmpEntity = listentity.get(i);
        Log.v("tmpEntity.getFrom()",tmpEntity.getFrom());
        Log.v("tmpEntity.getGossip()",tmpEntity.getGossip());
        Log.v("tmpEntity.getGossipid()",tmpEntity.getGossipid()+"");
        Log.v("tmpEntity.getSessionid()",tmpEntity.getSessionid());
        Log.v("tmpEntity.getSessiontype()",tmpEntity.getSessiontype()+"");
        Log.v("tmpEntity.getTo()",tmpEntity.getTo());
    }
}

}</pre>

啟動app打印結果如下因為數據庫里面的session表里面只有一條數據: </h2>


其他表的增刪改插參照DBHelper文件里面的實現吧,更復雜的查詢請用QueryBuilder,DBHelper里面也有可以參考。下面我將java工程和Android工程的下載地址給大家

五.查看數據庫
通過adb shell進入該程序的包路徑下,查看確實創建了dbname.db數據庫:


將數據庫dbname.db導出來用sqlite3在命令行查看


如下圖,SESSION_ENTITY、MQTT_CHAT_ENTITY、REPLAY_ENTITY是我們創建的那三個表


下面用select * from SESSION_ENTITY 可以查詢到我們插入的那條數據


回過頭來看最開始那張圖:


Jave Object 相當于我們生成的MqttChatEntity、SessionEntity、ReplayEntity通過greenDAO對象化的去訪問數據庫,其實最重要的還是java工程和DBHelper的編寫,因為其他都是自動生成的。

總結:
推薦大家一些鏈接: 官方提供的github地址,也有一個示例: https://github.com/greenrobot/greenDAO 
DaoExample和DaoExampleGenerator。你可以clone到本地,運行或者直接在github上直接瀏覽。如果你從git倉儲中檢出了DaoExample,可以直接像Android應用一樣運行它。正如你所看到的,它就是一個簡單的筆記本。可以添加新的note,或者點擊已存在的note進行刪除。
其他關于GreenDao好的文章: 
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1127/2069.html


源碼下載

來自:http://blog.csdn.net/csm_qz/article/details/44982463

 本文由用戶 xg48 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!