最近一直在研究一个第三方的开源框架,greenDaoMaster是一个移动开发的ORM框架,由于网上一直查不到使用资料,所以自己摸索总结下用法。

首先需要新建一个JAVA项目用来自动生成文件。需要导入greendao-generator-1.3.0.jar和freemarker.jar到项目中

示例代码如下:

/*
* 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);
} }

来分析这段代码:

Schema schema = new Schema(3, "de.greenrobot.daoexample");

Schema对象接受2个参数,第一个参数是DB的版本号,通过更新版本号来更新数据库。第二个参数是自动生成代码的包路径。包路径系统自动生成

在来看这段代码

Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addStringProperty("comment");
note.addDateProperty("date");

Entity表示一个实体可以对应成数据库中的表

系统自动会以传入的参数作为表的名字,这里表名就是NOTE

当然也可以自己设置表的名字,像这样:

order.setTableName("ORDERS");

接下来是一些字段参数设置。

如果想ID自动增长可以像这样:

  order.addIdProperty().autoincrement();

再来看这一段:

new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");

第一个参数是Schema对象,第二个参数是希望自动生成的代码对应的项目路径。

试了下src-gen这个文件夹必须手动创建,这里路径如果错了会抛出异常。

好了先别慌运行这段程序。新建一个Android项目名字是DaoExample,和刚才的JAVA项目保持在同一个文件夹下。

接着就可以运行刚才的JAVA程序,会看到src-gen下面自动生成了8个文件,3个实体对象,3个dao,1个DaoMaster,

1个DaoSession

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对象:

   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的方法:

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工具类:

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常量:

public class Constants {
public static final String DB_NAME = "note_db";
}

Note实体类:

// 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;
} }

greenDaoMaster的学习研究的更多相关文章

  1. BigPipe学习研究

    BigPipe学习研究   from: http://www.searchtb.com/2011/04/an-introduction-to-bigpipe.html 1. 技术背景 FaceBook ...

  2. Java 公平锁与非公平锁学习研究

    最近学习研究了一下Java中关于公平锁与非公平锁的底层实现原理,总结了一下. 首先呢,通过其字面意思,公平与非公平的评判标准就是付出与收获成正比(和社会中的含义差不多一个意思).放到程序中,尤其是 在 ...

  3. 详解 Facebook 田渊栋 NIPS2017 论文:深度强化学习研究的 ELF 平台

    这周,机器学习顶级会议 NIPS 2017 的论文评审结果已经通知到各位论文作者了,许多作者都马上发 Facebook/Twitter/Blog/ 朋友圈分享了论文被收录的喜讯.大家的熟人 Faceb ...

  4. C++的开源跨平台日志库glog学习研究(三)--杂项

    在前面对glog分别做了两次学习,请看C++的开源跨平台日志库glog学习研究(一).C++的开源跨平台日志库glog学习研究(二)--宏的使用,这篇再做个扫尾工作,算是基本完成了. 编译期断言 动态 ...

  5. C++的开源跨平台日志库glog学习研究(二)--宏的使用

    上一篇从整个工程上简单分析了glog,请看C++的开源跨平台日志库glog学习研究(一),这一篇对glog的实现代码入手,比如在其源码中以宏的使用最为广泛,接下来就先对各种宏的使用做一简单分析. 1. ...

  6. C++的开源跨平台日志库glog学习研究(一)

    作为C++领域中为数不多的好用.高效的.跨平台的日志工具,Google的开源日志库glog也算是凤毛麟角了.glog 是一个C++实现的应用级日志记录框架,提供了C++风格的流操作. 恰巧趁着五一我也 ...

  7. [大数据学习研究] 4. Zookeeper-分布式服务的协同管理神器

    本来这一节想写Hadoop的分布式高可用环境的搭建,写到一半,发现还是有必要先介绍一下ZooKeeper这个东西. ZooKeeper理念介绍 ZooKeeper是为分布式应用来提供协同服务的,而且Z ...

  8. 《A Survey on Transfer Learning》迁移学习研究综述 翻译

    迁移学习研究综述 Sinno Jialin Pan and Qiang Yang,Fellow, IEEE 摘要:   在许多机器学习和数据挖掘算法中,一个重要的假设就是目前的训练数据和将来的训练数据 ...

  9. 利用MONAI加速医学影像学的深度学习研究

    利用MONAI加速医学影像学的深度学习研究 Accelerating Deep Learning Research in Medical Imaging Using MONAI 医学开放式人工智能网络 ...

随机推荐

  1. CDOJ-10(栈的应用)

    In Galgame We Trust Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Othe ...

  2. 将分页功能从JSP页面中独立出来

    附带视频链接:http://www.tudou.com/programs/view/leaQ-YFl7W8/?bid=03&pid=2&resourceId=0_03_05_02

  3. eclipse 手动安装皮肤

    关于自动使用eclipse 主题不成功的给出现在手动的安装方法和jar包 http://pan.baidu.com/s/1kVNEiYr http://pan.baidu.com/s/1cyTZrS ...

  4. Asp.Net MVC--Controller激活2

    在使用MVC项目中,如果激活控制器,则就会向前台返回action执行的结果. 很多时候,根据需求,手动激活控制器来向客户端返回结果. 一.激活实例代码1 这是在Global文件中使用 var rout ...

  5. Chrome资源加载被Cancel的问题

    好个表久没写文章了. 做为一个砖业的砖工只能天天搬砖做些没有营养没有技术难度的活儿. 最近折腾个网站.发现一个很奇怪的问题- 各种图片的请求被取消了状态为Canceled. 顿时Chrome变成一个更 ...

  6. 那天有个小孩跟我说LINQ(四)转载

    1  LINQ TO SQL(代码下载)       我们以一个酒店管理系统的数据库为例子         表结构很简单:GuestInfo(客人信息表),Room(房间表),RoomType(房间类 ...

  7. StringToInt

    public class Stringtoint {    public static void stringtoint(String s){        //判断字符串是否为null和是否为空   ...

  8. iOS越狱系列(一):使用Reveal分析APP

    TOOLS 1.已越狱的设备,并且已安装了OpenSSH,MobileSubstrate等实用工具 Cydia源/Telesphoreo里有 里面有个包 可以基本集合所有开发工具提供库 2.mac o ...

  9. windows2008 x86 安装 32位oracle

    1.windows 2008 升级到sp2补丁 下载地址 : http://www.microsoft.com/zh-cn/download/confirmation.aspx?id=15278 2. ...

  10. C#一些小技巧

    在C#实现类似Typedef的所有功能 Typedef这个关键字,是比较好用的东西,因为有时候我们需要使用一些别名来帮助我们记忆某些结构体或者类的共用.(个人觉得这是C与C++唯一能吸引我的东西)为了 ...