Android之greenDao,一个orm的使用
转自: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的使用的更多相关文章
- 【转载】Android开源:数据库ORM框架GreenDao学习心得及使用总结
转载链接:http://www.it165.net/pro/html/201401/9026.html 最近在对开发项目的性能进行优化.由于项目里涉及了大量的缓存处理和数据库运用,需要对数据库进行频繁 ...
- [Android] Android 使用 Greendao 操作 db sqlite
Android 使用 Greendao 操作 db sqlite GreenDAO是一个开源的安卓ORM框架,能够使SQLite数据库的开发再次变得有趣.它减轻开发人员处理低级数据库需求,同时节省开发 ...
- Android 使用greenDAO 3.2.2 操作外部数据库
项目开发中有时需要用到一些写死的数据,如公司的产品信息之类的.这就需要我们先把数据库文件保存在资源文件夹下,然后当应用创建时将数据库文件拷到应用安装目录的/databases/文件夹下,然后再对数据进 ...
- 介介介是一个ORM
介个是一个ORM,介个ORM基于Dapper扩展. 为什么需要一个ORM呢? 支持简单的LINQ查询 但是不能连表查询,why?why?why?为什么不能连接查询 ^.^ ok.但是就是不支持.哈哈哈 ...
- 二维码合成,将苹果和安卓(ios和android)合成一个二维码,让用户扫描一个二维码就可以分别下载苹果和安卓的应用
因为公司推广的原因,没有合适的将苹果和安卓(ios和android)合成一个二维码的工具. 因为这个不难,主要是根据浏览器的UA进行判断,所以就自己开发了一个网站 网站名称叫:好推二维码 https ...
- Android 如何判断一个应用在运行(转)
Android 如何判断一个应用在运行 在一个应用中,或一个Service .Receiver中判断一个应用是否正在运行,以便进行一些相关的处理. 这个时候我们需要得到一个ActivityManag ...
- android studio 导入一个已有的android studio project作为lib使用
android studio 导入一个已有的android studio project作为lib使用 新项目来了. 需要搭建框架. android studio对我来说还是很陌生,之前一个项目在同事 ...
- Android Studio新建一个HelloWorld 程序(App)
Android Studio新建一个HelloWorld程序(App) 新建 或者直接启动程序(注:如果已有程序,此方法会直接打开最近一次关闭从程序) 更改App名 选择App运行平台 选择模板 更改 ...
- Android发展的一个重要方面Makefile分析
Android发展的一个重要方面Makefile分析 随着移动互联网的发展,移动开发也越来越吃香了.眼下最火的莫过于android.android是什么就不用说了,android自从开源以来,就受到非 ...
随机推荐
- day13--开发堡垒机
本节内容 项目实战:运维堡垒机开发 商业:<齐治--堡垒机> 前景介绍 https://www.cnblogs.com/alex3714/articles/ ...
- Mvc+Dapper+存储过程分页10万条数据
10万条数据采用存储过程分页实现(Mvc+Dapper+存储过程) 有时候大数据量进行查询操作的时候,查询速度很大强度上可以影响用户体验,因此自己简单写了一个demo,简单总结记录一下: 技术:Mvc ...
- vue后台管理框架
vue后台管理框架 系列教程<一步步带你做vue后台管理框架>第一课 github地址:vue-framework-wz 线上体验地址:立即体验 在如今的科技公司中有很多前端的需求都是要写 ...
- [Python]conda与 virtualenv虚拟环境配置
参考: Anaconda使用总结 Anacodna之conda与 virtualenv对比使用教程,创建虚拟环境 conda设置Python虚拟环境 python的virtualenv环境与使用 有时 ...
- Ubuntu16.04 14.04 配置caffe(CPU only)
1.安装依赖 sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-seria ...
- Docker化高可用redis集群
最近遇到部分系统因为redis服务挂掉,导致部分服务不可用.所以希望搭建一个redis集群镜像,把原先散落各处的redis服务器统一管理起来,并且保障高可用和故障自动迁移. 一:redis集群分类 大 ...
- ubuntu下安装flash player,浏览器观看视频,本人ubuntu版本14.04
首先去官网下载flash player安装包:flash_player_npapi_linux.x86_64,下载地址:https://get.adobe.com/cn/flashplayer/ 解压 ...
- Liunx 部署环境常用命令
在Linux环境中部署web项目中常用到一些命令,在此记录已做备用: 1. 查看当前工作目录: pwd [选项] 常用参数: pwd -P 显示出实际路径,而非使用连接(link)路径. 2. 列出目 ...
- android中MVP模式(一) - 清风明月的专栏 - CSDN博客
presenter 主持人.主导器 ====== 1. 明确需求,界面如下:可存,可根据id读取数据. 包结构图 2. 建立bean public class UserBean { private S ...
- 配置lambda
=========== 添加 apply plugin: 'me.tatarka.retrolambda' 添加 compileOptions { sourceCompatibilit ...