最近一直在研究一个第三方的开源框架,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");
在来看这段代码
Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addStringProperty("comment");
note.addDateProperty("date");
系统自动会以传入的参数作为表的名字,这里表名就是NOTE
当然也可以自己设置表的名字,像这样:
order.setTableName("ORDERS");
如果想ID自动增长可以像这样:
order.addIdProperty().autoincrement();
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
试了下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
来看看如何使用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;
}
}
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 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 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 list){
if(list == null || list.isEmpty()){
return;
}
noteDao.getSession().runInTx(new Runnable() {
@Override
public void run() {
for(int i=0; i
public class Constants {
public static final String DB_NAME = "note_db";
}
// 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;
}
}