转自: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;
} }

Android之greenDao,一个orm的使用的更多相关文章

  1. 【转载】Android开源:数据库ORM框架GreenDao学习心得及使用总结

    转载链接:http://www.it165.net/pro/html/201401/9026.html 最近在对开发项目的性能进行优化.由于项目里涉及了大量的缓存处理和数据库运用,需要对数据库进行频繁 ...

  2. [Android] Android 使用 Greendao 操作 db sqlite

    Android 使用 Greendao 操作 db sqlite GreenDAO是一个开源的安卓ORM框架,能够使SQLite数据库的开发再次变得有趣.它减轻开发人员处理低级数据库需求,同时节省开发 ...

  3. Android 使用greenDAO 3.2.2 操作外部数据库

    项目开发中有时需要用到一些写死的数据,如公司的产品信息之类的.这就需要我们先把数据库文件保存在资源文件夹下,然后当应用创建时将数据库文件拷到应用安装目录的/databases/文件夹下,然后再对数据进 ...

  4. 介介介是一个ORM

    介个是一个ORM,介个ORM基于Dapper扩展. 为什么需要一个ORM呢? 支持简单的LINQ查询 但是不能连表查询,why?why?why?为什么不能连接查询 ^.^ ok.但是就是不支持.哈哈哈 ...

  5. 二维码合成,将苹果和安卓(ios和android)合成一个二维码,让用户扫描一个二维码就可以分别下载苹果和安卓的应用

    因为公司推广的原因,没有合适的将苹果和安卓(ios和android)合成一个二维码的工具. 因为这个不难,主要是根据浏览器的UA进行判断,所以就自己开发了一个网站 网站名称叫:好推二维码  https ...

  6. Android 如何判断一个应用在运行(转)

    Android 如何判断一个应用在运行  在一个应用中,或一个Service .Receiver中判断一个应用是否正在运行,以便进行一些相关的处理. 这个时候我们需要得到一个ActivityManag ...

  7. android studio 导入一个已有的android studio project作为lib使用

    android studio 导入一个已有的android studio project作为lib使用 新项目来了. 需要搭建框架. android studio对我来说还是很陌生,之前一个项目在同事 ...

  8. Android Studio新建一个HelloWorld 程序(App)

    Android Studio新建一个HelloWorld程序(App) 新建 或者直接启动程序(注:如果已有程序,此方法会直接打开最近一次关闭从程序) 更改App名 选择App运行平台 选择模板 更改 ...

  9. Android发展的一个重要方面Makefile分析

    Android发展的一个重要方面Makefile分析 随着移动互联网的发展,移动开发也越来越吃香了.眼下最火的莫过于android.android是什么就不用说了,android自从开源以来,就受到非 ...

随机推荐

  1. AWS 使用经验

    掐指一算,自己第一次使用 AWS 已经是两年前的事情了,这也是云计算和大数据等技术迅猛发展的两年.这期间,大抵间间断断地使用着,FreeTier Instance 也运行快一年了,马上进入收费周期.虽 ...

  2. Ubuntu 下 vi 输入方向键会变成 ABCD 的解决方法

    Ubuntu 下 vi 输入方向键会变成 ABCD,这是 Ubuntu 预装的是 vim tiny 版本,安装 vim full 版本即可解决. 先卸载vim-tiny: $ sudo apt-get ...

  3. .NetCore关于Cap(RabbitMQ)结合MySql使用出现MySql相关类冲突问题解决办法

    问题还原 引用了 DotNetCore.CAP.MySql MySql.Data.EntityFrameworkCore 在使用MySql相关对象的时候会出现如下冲突,在命名空间加入伪空间名称是不能解 ...

  4. 11 个最佳 jQuery 模拟滚动条插件 scrollbar

    1.  Windows:全屏窗口滚动插件 该插件可以很好地实现全屏滚动,每滚动一次即为一屏.比如,用户浏览下一屏幕内容时,只需手动滚动到某一位置,该插件会自动滚动显示下一屏全部内容.对于浏览类似于PP ...

  5. 【AtCoder】ARC091

    C - Flip,Flip, and Flip...... 只有一个这一个是反面 只有一行那么除了两边以外都是反面 否则输出\((N - 2)*(M - 2)\) #include <bits/ ...

  6. 038 spark中使用sparksql对日志进行分析(属于小案例)

    一:使用sparksql开发 1.sparksql开发的两种方式 HQL:SQL语句开发 eq : sqlContext.sql("xxxx") DSL : sparkSql中Da ...

  7. 社会地位即服务, Status as a Service (一): 社交网络是一种 ICO 行为?

    上周,看到 Eugene Wei 又发了一篇长文,Status as a Service (StaaS).状态即服务?服务器的状态吗?不知所言.抱着好奇,我打开了这篇文章,一看就是 3 个小时!

  8. webpack1.x环境配置与打包基础【附带各种 "坑" 与解决方案!持续更新中...】

    首先介绍传统模块化开发的主流方案: 1.基与CMD的sea.js,玉伯提出的解决方案,据说原来京东团队在使用.用时才定义,就近加载. 2.基于AMD的require.js,之前在用.提前声明与定义.国 ...

  9. CentOS 7下升级MySQL5.7.23的一个坑

    发现CentOS 7下升级MySQL5.7.23的一个坑,以前面升级到MySQL 5.7.23的一个集群为例 在我们环境下打开文件描述符个数的参数open_files_limit在MySQL 5.6. ...

  10. 【BZOJ-4180】字符串计数 后缀自动机 + 矩阵乘法

    4180: 字符串计数 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 146  Solved: 66[Submit][Status][Discuss] ...