转自: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. Windows下SVN服务器搭建方法整理(apache)

    http://skydream.iteye.com/blog/437959 http://www.cnblogs.com/liuke209/archive/2009/09/23/1572858.htm ...

  2. winform解析json

    在使用C#开发爬虫程序时,会遇到需要解析json字符串的情况.对于json字符串可以使用正则表达式的形式进行解析,更为方便的方法是使用Newtonsoft.Json来实现. Nuget添加应用包 在工 ...

  3. 006 jquery过滤选择器-----------(可见性过滤选择器)

    1.介绍 2.程序 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> < ...

  4. ubuntu下spark安装配置

    一.安装vmware虚拟机 二.在虚拟机上安装ubuntu12.04操作系统 三.安装jdk1.8.0_25 http://www.oracle.com/technetwork/java/javase ...

  5. valgrind 内存调试工具

    一.valgrind 是运行在linux系统下的内存调试工具,支持很多对象:memcheck.addrcheck.cachegrind.Massif.helgrind.Callgrind等.使用val ...

  6. C++雾中风景10:聊聊左值,纯右值与将亡值

    C++11的版本在类型系统上下了很大的功夫,添加了诸如auto,decltype,move等新的关键词来简化代码的编写与降低阅读代码的难度.为了更好的理解这些新的语义,笔者确定通过几篇文章来简单窥探一 ...

  7. Linux设备驱动之USB

    Linux驱动框架分析(一)        事实上,Linux的设备驱动都遵循一个惯例——表征驱动程序(用driver更贴切一些,应该称为驱动器比较好吧)的结构体,结构体里面应该包含了驱动程序所需要的 ...

  8. 添加第一个控制器(Controllers)

    在MVC体系架构中,输入请求是由控制器Controller来处理的(负责处理浏览器请求,并作出响应).在ASP.NET MVC中Controller本身是一个类(Class)通常继承于System.W ...

  9. WordPress 建站教程:新手搭建 WordPress个人博客图文教程(完全版)

    前言 WordPress 作为动态博客的代表,至今已经有十几年历史,而且一直在更新发展中,功能强大,插件和主题丰富,WordPress搭建使用也很方便.作为个人站长和博主,很多都是从 WordPres ...

  10. [Java]struts2-spring整合时配置监听器

    1.struts2-spring整合时配置监听器 [在web.xml中] <!-- 上下文载入器监听器,确保web服务器启动时,直接完成spring容器的初始化 --/> [Ctrl + ...