1、android orm之greendao

前提:最近写android项目,android自带数据库api有点复杂,于是偷懒用了greendao。greendao好处自己查,这里不赘述,但是零基础的的我用起来还是费了3天的功夫,取之于网络,特在此奉献与网络。

1、通过daoGenerator生成所需要的关键文件

步骤1、新建的java工程,起名daoGenerator

步骤2:导入两个jar包,分别是freemarker-2.3.20.jar和greendao-generator-1.3.1.jar,下载路径:http://search.maven.org,你可以在这里搜索上述两个包,自己导入到java工程中,

导入的时候记着不要有中文路径

步骤3:新建daoGenerator.java文件,文件格式如下

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;


public class daoGenerator {

    public static void main(String[] args) throws Exception {
        Schema schema = new Schema(1,"com.example.menu");
        
        addMenuDetail(schema);
        addMenuTable(schema);

        new DaoGenerator().generateAll(schema, "./");
    }
    
    private static void addMenuTable(Schema schema)
    {
        Entity menuTable = schema.addEntity("MenuTable");
        menuTable.addStringProperty("menuName");//菜单的名称(周一早餐通用版)
        menuTable.addIntProperty("menuType");//0早餐 1午餐 2晚餐
        menuTable.addLongProperty("menuId").primaryKey().autoincrement();//菜单id
        menuTable.addStringProperty("menuCreateTime");//菜单创建时间
        menuTable.addLongProperty("storeId");//店铺的编号        
    }
    
    
    private static void addMenuDetail(Schema schema) {
        Entity menuDetail = schema.addEntity("MenuDetail");
        menuDetail.addStringProperty("menuDateId");
        menuDetail.addLongProperty("menuId");//菜单id
        menuDetail.addIntProperty("widgetId");//控件id
        menuDetail.addStringProperty("type");//控件类型:textview、pic、line、verticalLine、theme、tips
        menuDetail.addStringProperty("name");//控件内容 "疙瘩汤"
        menuDetail.addDoubleProperty("x");//x
        menuDetail.addDoubleProperty("y");//y
    }
    
    

}

该工程运行完毕会在当前目录下产生一个文件夹com,进入example再进入到menu(为什么会产生这样一个文件夹,这是由我们在程序中 Schema schema = new Schema(1,"com.example.menu"), new DaoGenerator().generateAll(schema, "./");这两行决定的,如果你运行出错,请查看你是不是路径写错),可以发现生成如下几个文件:

简要说明:menuDetail和menuTable就是我们在daoGenerator中指定生成的表,在生成的文件中每张表分别对应两个文件,举例:表menuTable对应的两个文件一个是menuTable,一个是menuTableDao。

menuTable.java文件主要是menuTable中取得和设置列中元素的方法,见下图,注意:这是自动生成的代码,如果要修改列中元素名称可以在daoGenerator中修改:

 1 package com.ShanFuBao.SmartCall.menu;
 2 
 3 // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. 
 4 /**
 5  * Entity mapped to table MENU_TABLE.
 6  */
 7 public class MenuTable {
 8 
 9     private String menuName;
10     private Integer menuType;
11     private Long menuId;
12     private String menuCreateTime;
13     private Long storeId;
14 
15     public MenuTable() {
16     }
17 
18     public MenuTable(Long menuId) {
19         this.menuId = menuId;
20     }
21 
22     public MenuTable(String menuName, Integer menuType, Long menuId, String menuCreateTime, Long storeId) {
23         this.menuName = menuName;
24         this.menuType = menuType;
25         this.menuId = menuId;
26         this.menuCreateTime = menuCreateTime;
27         this.storeId = storeId;
28     }
29 
30     public String getMenuName() {
31         return menuName;
32     }
33 
34     public void setMenuName(String menuName) {
35         this.menuName = menuName;
36     }
37 
38     public Integer getMenuType() {
39         return menuType;
40     }
41 
42     public void setMenuType(Integer menuType) {
43         this.menuType = menuType;
44     }
45 
46     public Long getMenuId() {
47         return menuId;
48     }
49 
50     public void setMenuId(Long menuId) {
51         this.menuId = menuId;
52     }
53 
54     public String getMenuCreateTime() {
55         return menuCreateTime;
56     }
57 
58     public void setMenuCreateTime(String menuCreateTime) {
59         this.menuCreateTime = menuCreateTime;
60     }
61 
62     public Long getStoreId() {
63         return storeId;
64     }
65 
66     public void setStoreId(Long storeId) {
67         this.storeId = storeId;
68     }
69 
70 }
View Code

menuTableDao.java文件就是执行的对表进行增删改查的封装。

  1 package com.ShanFuBao.SmartCall.menu;
  2 
  3 import android.database.Cursor;
  4 import android.database.sqlite.SQLiteDatabase;
  5 import android.database.sqlite.SQLiteStatement;
  6 
  7 import de.greenrobot.dao.AbstractDao;
  8 import de.greenrobot.dao.Property;
  9 import de.greenrobot.dao.internal.DaoConfig;
 10 
 11 import com.ShanFuBao.SmartCall.menu.MenuTable;
 12 
 13 // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
 14 /** 
 15  * DAO for table MENU_TABLE.
 16 */
 17 public class MenuTableDao extends AbstractDao<MenuTable, Long> {
 18 
 19     public static final String TABLENAME = "MENU_TABLE";
 20 
 21     /**
 22      * Properties of entity MenuTable.<br/>
 23      * Can be used for QueryBuilder and for referencing column names.
 24     */
 25     public static class Properties {
 26         public final static Property MenuName = new Property(0, String.class, "menuName", false, "MENU_NAME");
 27         public final static Property MenuType = new Property(1, Integer.class, "menuType", false, "MENU_TYPE");
 28         public final static Property MenuId = new Property(2, Long.class, "menuId", true, "MENU_ID");
 29         public final static Property MenuCreateTime = new Property(3, String.class, "menuCreateTime", false, "MENU_CREATE_TIME");
 30         public final static Property StoreId = new Property(4, Long.class, "storeId", false, "STORE_ID");
 31     };
 32 
 33 
 34     public MenuTableDao(DaoConfig config) {
 35         super(config);
 36     }
 37     
 38     public MenuTableDao(DaoConfig config, DaoSession daoSession) {
 39         super(config, daoSession);
 40     }
 41 
 42     /** Creates the underlying database table. */
 43     public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
 44         String constraint = ifNotExists? "IF NOT EXISTS ": "";
 45         db.execSQL("CREATE TABLE " + constraint + "'MENU_TABLE' (" + //
 46                 "'MENU_NAME' TEXT," + // 0: menuName
 47                 "'MENU_TYPE' INTEGER," + // 1: menuType
 48                 "'MENU_ID' INTEGER PRIMARY KEY AUTOINCREMENT ," + // 2: menuId
 49                 "'MENU_CREATE_TIME' TEXT," + // 3: menuCreateTime
 50                 "'STORE_ID' INTEGER);"); // 4: storeId
 51     }
 52 
 53     /** Drops the underlying database table. */
 54     public static void dropTable(SQLiteDatabase db, boolean ifExists) {
 55         String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'MENU_TABLE'";
 56         db.execSQL(sql);
 57     }
 58 
 59     /** @inheritdoc */
 60     @Override
 61     protected void bindValues(SQLiteStatement stmt, MenuTable entity) {
 62         stmt.clearBindings();
 63  
 64         String menuName = entity.getMenuName();
 65         if (menuName != null) {
 66             stmt.bindString(1, menuName);
 67         }
 68  
 69         Integer menuType = entity.getMenuType();
 70         if (menuType != null) {
 71             stmt.bindLong(2, menuType);
 72         }
 73  
 74         Long menuId = entity.getMenuId();
 75         if (menuId != null) {
 76             stmt.bindLong(3, menuId);
 77         }
 78  
 79         String menuCreateTime = entity.getMenuCreateTime();
 80         if (menuCreateTime != null) {
 81             stmt.bindString(4, menuCreateTime);
 82         }
 83  
 84         Long storeId = entity.getStoreId();
 85         if (storeId != null) {
 86             stmt.bindLong(5, storeId);
 87         }
 88     }
 89 
 90     /** @inheritdoc */
 91     @Override
 92     public Long readKey(Cursor cursor, int offset) {
 93         return cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2);
 94     }    
 95 
 96     /** @inheritdoc */
 97     @Override
 98     public MenuTable readEntity(Cursor cursor, int offset) {
 99         MenuTable entity = new MenuTable( //
100             cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // menuName
101             cursor.isNull(offset + 1) ? null : cursor.getInt(offset + 1), // menuType
102             cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2), // menuId
103             cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // menuCreateTime
104             cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4) // storeId
105         );
106         return entity;
107     }
108      
109     /** @inheritdoc */
110     @Override
111     public void readEntity(Cursor cursor, MenuTable entity, int offset) {
112         entity.setMenuName(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0));
113         entity.setMenuType(cursor.isNull(offset + 1) ? null : cursor.getInt(offset + 1));
114         entity.setMenuId(cursor.isNull(offset + 2) ? null : cursor.getLong(offset + 2));
115         entity.setMenuCreateTime(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
116         entity.setStoreId(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
117      }
118     
119     /** @inheritdoc */
120     @Override
121     protected Long updateKeyAfterInsert(MenuTable entity, long rowId) {
122         entity.setMenuId(rowId);
123         return rowId;
124     }
125     
126     /** @inheritdoc */
127     @Override
128     public Long getKey(MenuTable entity) {
129         if(entity != null) {
130             return entity.getMenuId();
131         } else {
132             return null;
133         }
134     }
135 
136     /** @inheritdoc */
137     @Override    
138     protected boolean isEntityUpdateable() {
139         return true;
140     }
141     
142 }
View Code

还有两个文件没有介绍,分别是DaoMaster.java和DaoSessi.java文件,这两个文件很重要,也是daoGenerator工程自动生成的,

daoMaster文件是干嘛的,看下图:

明白了吗?他知道你创建的所有的dao对象,对,通过他,你可以得到你想要操作的表格对应的对象。

daoSession文件又是干嘛的??通过session你可以得到和删除dao对象。

到这里应该明白了:

我们以往通过sql去创建的表格,在这里通过daoGennerator的java工程来完成

②我们通过sql对表格的操作,可以通过daoMaser得到表格,然后通过daoSession获取到具体的对象,这样就完成了数据库到对象的映射,对应了orm的主题。

2、避开sql使用dao来执行表操作

OpenHelper helper = new DaoMaster.DevOpenHelper(context,"test_db", null);  

daoMaster = new DaoMaster(helper.getWritableDatabase());  

daoSession = daoMaster.newSession();  

menuTableDao = daoSession.getMenuTableDao();

menuDetailDao = daoSession.getMenuDetailDao();

一些简单的使用方法如下

 1 //查看对应的menuTable表是否存在
 2             QueryBuilder qb = menuDetailDao.queryBuilder();
 3             qb.where(MenuDetailDao.Properties.MenuDateId.eq(CommonUtils.getNowDateString()+menu_type));
 4             List listResult = qb.list();
 5             
 6             QueryBuilder qbAll = menuDetailDao.queryBuilder();
 7             qbAll.orderAsc(MenuDetailDao.Properties.MenuDateId);
 8             List listResultAll = qbAll.list();
 9             for(int k =0;k<listResultAll.size();k++)
10             {
11                 MenuDetail menu_detail_entity = (MenuDetail) listResultAll.get(k);
12                 CommonUtils.LogWuwei(tag, menu_detail_entity.getName()+"   "+
13                         menu_detail_entity.getMenuDateId());
14             }
15             
View Code

 

3、自学的时候借阅了很多资料,如果恰巧你刚接触到,你会用到的:

1、http://my.oschina.net/cheneywangc/blog/196354 greendao讲义,开源中国上的好文章

2、http://www.sllbeta.com/android/3/

3、http://greendao-orm.com/ 这个是官网,最权威的网站了

4、我是从哪里听说到这个greendao的呢,这得益于github上一个开源工程,在这个开源工程中,汇聚了android开发过程中开发者都有可能用到的,见下网址:

https://github.com/Trinea/android-open-project

5、http://blog.csdn.net/lan120576664/article/details/36204833(适合新手看看)

4、赠送所有开发者一句话,多看官网文档,如果需要看官网api,推荐一个工具,就是mac下的dash,dash支持代码片段和官网api(api包括很多,绝对是你想象不到的)

原文地址:https://www.cnblogs.com/kunyashaw/p/4099310.html