最近一直在研究一个第三方的开源框架,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 keywordorder.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;@Overridepublic 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() {@Overridepublic 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;}}

转载于:https://www.cnblogs.com/krislight1105/p/3748373.html

greenDaoMaster的学习研究相关推荐

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

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

  2. 三维点云的深度学习研究综述

    作者丨aaa 来源丨https://zhuanlan.zhihu.com/p/455210291 编辑丨3D视觉工坊 摘要 点云学习由于在计算机视觉.自动驾驶.机器人等领域的广泛应用,近年来受到越来越 ...

  3. 《强化学习周刊》第32期:上海交大华为 | 可解释强化学习研究综述

    No.32 智源社区 强化学习组 强 化 学  习 研究 观点 资源 活动 关于周刊 强化学习作为人工智能领域研究热点之一,其研究进展与成果也引发了众多关注.为帮助研究与工程人员了解该领域的相关进展和 ...

  4. 从OpenAI看深度学习研究前沿

    版权说明:本文为原创文章,未经作者允许不得转载. 1 前言 想必很多知友都知道OpenAI这家初创公司.OpenAI是2015年底刚成立的人工智能公司,由Elon Musk领投,号称有10亿美金的投资 ...

  5. NeurIPS 2019 少样本学习研究亮点全解析

    作者:Angulia Chao 编辑:Joni Zhong 少样本学习(Few-Shot Learning)是近两年来非常有研究潜力的一个子方向,由于深度学习在各学科交叉研究与商业场景都有比较普遍的应 ...

  6. Yoshua Bengio团队最新强化学习研究:智能体通过与环境交互,「分离」变化的独立可控因素

    原文来源:arXiv 作者:Valentin Thomas.Emmanuel Bengio∗.William Fedus.Jules Pondard.Philippe Beaudoin.Hugo La ...

  7. 诺亚面向语音语义的深度学习研究进展

    本文来自华为诺亚方舟实验室资深专家刘晓华在携程技术中心主办的深度学习Meetup中的主题演讲,介绍了华为诺亚面向语音语义的深度学习进展. 本次演讲简要回顾了深度学习近十年进展,重点介绍华为诺亚方舟实验 ...

  8. 一次完整的渗透测试仅供学习研究

    声明:本文仅限学习研究讨论,切忌做非法乱纪之事 Web打点 渗透测试中,Web端最常见的问题大多出现在弱口令.文件上传.未授权.任意文件读取.反序列化.模版漏洞等方面.因此,我们着重围绕这些方面进行渗 ...

  9. 设计一款博弈类游戏的人机对战算法、策略_卡牌游戏八合一,华人团队开源强化学习研究平台RLCard...

    雷锋网 AI 科技评论按:在过去的两三年中,我们经常听说人工智能在棋牌类游戏(博弈)中取得新的成果,比如基于深度强化学习的 AlphaGo 击败了人类世界冠军,由 AlphaGo 进化而来的 Alph ...

  10. 未能加载程序集或它的一个依赖项_英伟达发布kaolin:一个用于加速3D深度学习研究的PyTorch库...

    由于大多数现实环境是三维的,因此理想情况下,应针对3D数据训练旨在分析视频或现实环境中的完整任务的深度学习模型.诸如机器人,自动驾驶汽车,智能手机和其他设备之类的技术工具目前正在产生越来越多的3-D数 ...

最新文章

  1. 服务器硬件电路设计书籍,家庭网关硬件接口电路设计大全——电路精选(3)...
  2. opcua客户端实现断线重连_干货:通过OPC UA协议访问西门子1500数据
  3. boost::locale::calendar用法的测试程序
  4. python sdk怎么用_如何使用七牛Python SDK写一个同步脚本及使用教程
  5. 深度学习去燥学习编码_我们问了15,000个人,他们是谁,以及他们如何学习编码
  6. WCF 客户端连接慢
  7. 【获奖公布】元老选手心得分享:请把自己看成一位出色的工程师
  8. Linux中用yum安装MySQL方法
  9. 城市综合杆道路智慧路灯多杆合一项目解决方案解析
  10. 无奈人心渐开明 贪嗔痴恨爱恶欲
  11. 查看dmp文件oracle版本,Oracle的DMP文件修改版本号
  12. oracle进行列合并,oracle列合并的实现方法
  13. win10 下 pdfium编译 VS2017
  14. 最受欢迎的webgl 3d引擎
  15. 魔法宝石(动态规划)
  16. SVN初学者学习使用文章(转自文档)
  17. 李弘毅机器学习笔记:第十五章—半监督学习
  18. 数据从excel导入ORACLE的4个方法
  19. 我们的宇宙可能是一个3.9999…
  20. 小熊派学习:手册查询和ADC深入使用

热门文章

  1. 【hdu1018】Big Number(求n!的位数----斯大林公式/log函数)
  2. hdoj2044:一只小蜜蜂(递推)
  3. java radix sort_Java RadixSort
  4. ant 日期组件中文_Vue3开源组件库,今天“它们”来了
  5. C/C++[codeup 1923]排序
  6. TensorFlow by Google神经网络深度学习的 Hello World Machine Learning Foundations: Ep #1 - What is ML?
  7. 漫话:如何给女朋友解释什么是反向代理、正向代理?
  8. 文件怎么更新_干货!Win10更新总失败?学会这三招搞定它
  9. php 判断访问类型,php如何判断访问系统的用户设备类型(代码示例)
  10. windows会不会被linux取代,深度Linux系统会取代Windows系统吗?