AndroidGreenDao使用个人心得


对AndroidGreenDao觉得用的还算方便,总体来说没有第三方jar包方便,请原谅鄙人比较懒,好啦,现在说下用法

首先我们需要建一个java工程,例如:DaoExampleGenerator

在其中建一个libs文件夹,存放jar

这里需要2个jar  freemarker-2.3.21.jar greendao-generator-1.3.1.jar,引如2个jar到其中

http://search.maven.org/#search%7Cga%7C1%7CgreenDao 

下载greendao-generator-1.3.0.jar 和greendao-1.3.7.jar

 

http://mvnrepository.com/artifact/org.freemarker/freemarker

下载freemarker-2.3.20.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 {
//		// 该方法第一个参数用来更新数据库版本号,第二个参数为要生成的DAO类所在包路径。
//		Schema schema = new Schema(1000, "com.example.androidgreendao");
//		// 然后进行建表和设置要生成DAO文件的目标工程的项目路径。
//		addNote(schema);
//		addCustomerOrder(schema);
//		//其中src-gen这个目录名需要在运行前手动创建,否则会报错。
//		new DaoGenerator().generateAll(schema, "../AndroidGreenDao/greendao");
		
		
		 Schema schema = new Schema(1, "com.example.androidgreendao.mode");
		 
	        addNote(schema);
	        addCustomerOrder(schema);
	        // set dao class generate package
	        schema.setDefaultJavaPackageDao("com.example.androidgreendao.dao");
	        // keep custom code block
	        schema.enableKeepSectionsByDefault();
	        new DaoGenerator().generateAll(schema, "../AndroidGreenDao/src");//这里是你的android项目的src文件夹
	}

//	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");
//		//默认表名就是类名,也可以自定义表名
//		/**
//		 * greenDAO会自动根据实体类属性创建表字段,
//		 * 并赋予默认值。
//		 * 例如在数据库方面的表名和列名都来源于实体类名和属性名。
//		 * 默认的数据库名称是大写使用下划线分隔单词,而不是在Java中使用的驼峰式大小写风格。
//		 * 例如,一个名为“CREATIONDATE”属性将成为一个数据库列“CREATION_DATE”。
//		 */
//		order.setTableName("ORDERS"); // "ORDER" is a reserved keyword
//		order.addIdProperty();
		设置一个自增长ID列为主键:
		dao.addIdProperty().primaryKey().autoincrement();
//		//设置其他各种类型的属性:
//		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);
//	}

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

然后创建你的Android工程 例如AndroidGreenDao,将greendao-1.3.7.jar导入
运行java,刷新下你的Android工程便可以看到dao和mode包,里面有8个文件,否则会报错,这里会报java错误,最多就说找不到文件夹

在Application 实现得到DaoMaster和DaoSession的方法,并且让你项目的Application name它

package com.example.androidgreendao;

import android.app.Application;
import android.content.Context;

import com.example.androidgreendao.dao.DaoMaster;
import com.example.androidgreendao.dao.DaoMaster.OpenHelper;
import com.example.androidgreendao.dao.DaoSession;
import com.example.androidgreendao.vo.Constants;

public class MyApplication extends Application {
	 
	private static MyApplication 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;
	}
}

创建一个Constants类,存放你的数据库名称

package com.example.androidgreendao.vo;

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

如果你不写DBHelper.那么在Activity 的 oncreate中是这样的

查询表中前四条

		MyApplication app = (MyApplication) getApplication();
		DaoSession daoSession = app.getDaoSession(this);
		CustomerDao customerDao = daoSession.getCustomerDao();

		ListView lv = (ListView) findViewById(R.id.listView1);
		List<String> data = new ArrayList<String>();
        data.add(customerDao.loadAll().get(0).getName());
        data.add(customerDao.loadAll().get(1).getName());
        data.add(customerDao.loadAll().get(2).getName());
        data.add(customerDao.loadAll().get(3).getName());
		lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,data));
//		for (int i = 0; i < 10; i++) {
//			Customer customer = new Customer();
//			customer.setName("大S" + i);
//			customerDao.insertOrReplace(customer);
//		}

插入

        MyApplication app = (MyApplication) getApplication();
		DaoSession daoSession = app.getDaoSession(this);
		CustomerDao customerDao = daoSession.getCustomerDao();

	
		
		for (int i = 0; i < 10; i++) {
			Customer customer = new Customer();
			customer.setName("大S" + i);
			customerDao.insertOrReplace(customer);
		}
	
当然正规的写法应该是使用DBHelper
package com.example.androidgreendao.util;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.example.androidgreendao.MyApplication;
import com.example.androidgreendao.dao.DaoSession;
import com.example.androidgreendao.dao.NoteDao;
import com.example.androidgreendao.mode.Note;

public class DBHelper
{
	private static DBHelper instance;
	private static Context appContext;
	private DaoSession mDaoSession;
	private NoteDao noteDao;
	
	
	private DBHelper() {
	}

	public static DBHelper getInstance(Context context) {
		if (instance == null) {
			instance = new DBHelper();
			if (appContext == null){
				appContext = context.getApplicationContext();
			}
			instance.mDaoSession = MyApplication.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("test", "delete");
	}
	
	public void deleteNote(Note note){
		noteDao.delete(note);
	}
	
}

在activity中实例化以后就可以直接使用了,速度和效率就不说了,希望有能提出交流意见的,帮助优化代码

下载文件也给大家了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值