greenDao基本搭建和使用

    最近闲得发慌,研究下android框架,蛮早就听说过greendao,一直没接触,这会儿工夫来捯饬捯饬。
    作为一个菜鸟,不求所以然,先会用,再慢慢体会他设计的精妙在哪里。
    个人验证通过可行的方法。
    平台: eclipse+adt。
    包: greendao-2.0.0.jar,greendao-generator-2.0.0.jar,freemarker,jar.
  1. 创建一个java project 导入中添加两个包,freemarker.jar 以及greendao-generator-2.0.0.jar
greenDao基本搭建和使用

  2:创建MyGenerator.java 文件,执行 run as  java application

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;

public class MyGenerator {
 
    public static void main(String[] args) throws Exception {
        // first parameter for version, <span></span> second for default generate package
        Schema schema = new Schema(4, "com.xckevin.example.model");
 
        addNote(schema);
        addCustomerOrder(schema);
        addUser(schema);
        addVersion(schema);
        // set dao class generate package
        schema.setDefaultJavaPackageDao("com.xckevin.example.dao");
        // keep custom code block
        schema.enableKeepSectionsByDefault();
        new DaoGenerator().generateAll(schema, "../greenDaoJava/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 addUser(Schema schema) {
        Entity user = schema.addEntity("User");
        user.setTableName("t_user");
        user.addIdProperty();
        user.addStringProperty("account").unique();
        user.addStringProperty("password");
        user.addDateProperty("birthday");
        user.addShortProperty("gender");
        user.addIntProperty("height");
        user.addFloatProperty("weight");
        user.addDateProperty("registerTime");
        user.implementsInterface("Jsonable<User>");
    }
    private static void addVersion(Schema schema){
    	 Entity version = schema.addEntity("Version");
         version.addIdProperty();
         version.addLongProperty("versionNo").unique();
         version.addStringProperty("sql").unique();
         version.addStringProperty("desc");
    }
 
    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);
        
//        Property orderId=customer.addLongProperty("orderId").notNull().getProperty();
//        customer.addToOne(order, orderId);
        
        ToMany customerToOrders = customer.addToMany(order, customerId);
        customerToOrders.setName("orders");
        customerToOrders.orderAsc(orderDate);
    }
 
}

 3. 执行之后,输出控台Log ,刷新java project 生成Dao层文件以及model 层文件。

Processing schema version 4...
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\NoteDao.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\model\Note.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\CustomerDao.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\model\Customer.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\OrderDao.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\model\Order.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\UserDao.javaWritten E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\model\User.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\VersionDao.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\model\Version.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\DaoMaster.java
Written E:\DFE_Adroid4\greenDaoJava\src\com\xckevin\example\dao\DaoSession.java 

greenDao基本搭建和使用

4. 将生成的model以及到复制赞贴到android project中,android project 中需要添加greendao-2.0.0.jar包

然后就可以再android项目中使用了,测试案例:

package com.example.greendaoandroid;

import android.app.Activity;

public abstract class BaseActivity extends Activity{
	public static final String DB_NAME="notes_db";
}
package com.example.greendaoandroid;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Property;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.xckevin.example.dao.CustomerDao;
import com.xckevin.example.dao.DaoMaster;
import com.xckevin.example.dao.DaoMaster.DevOpenHelper;
import com.xckevin.example.dao.DaoSession;
import com.xckevin.example.dao.NoteDao;
import com.xckevin.example.dao.OrderDao;
import com.xckevin.example.model.Customer;
import com.xckevin.example.model.Note;
import com.xckevin.example.model.Order;

public class MainActivity extends BaseActivity {

	
	private DaoSession daoSession;
	private NoteDao noteDao;
	private OrderDao orderDao;
	private CustomerDao cusDao;
	
	public static int count=1;
	private final static String CUS_TEST="张山";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initDao();
		
		noteDao.deleteAll();
		orderDao.deleteAll();//清空数据 方便测试
		cusDao.deleteAll();//清空数据 方便测试
		Customer cus=new Customer(null, CUS_TEST);//一对多插入主
		cusDao.insert(cus);//插入一个客户
		
		Button btnInsert=(Button)findViewById(R.id.btnInsert);
		final TextView result=(TextView)findViewById(R.id.tvShow);
		//单个插入测试
		btnInsert.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Note note = new Note(null, "noteText"+(count), "评论"+(count++), new Date());  
				noteDao.insert(note);  
				List<Note> notes=noteDao.queryBuilder().list();
				result.setText("");
				for(Note n:notes){
					result.append(n.toString()+"\n");//重写了实体的toString(),方便测试
				}
			}
		});
	Button	btnInsertOneToMany=(Button)findViewById(R.id.btnInsertOneToMany);
	//一对多插入测试
	btnInsertOneToMany.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {

				result.setText("");
				
				Customer mcus=cusDao.queryBuilder().where(
						CustomerDao.Properties.Name.eq(CUS_TEST)).list().get(0);
				
				Order od=new Order(null, new Date(),mcus.getId());
				orderDao.insert(od);
//				for(Order d:orderDao.loadAll()){
//					result.append(d.toString()+"\n");
//				}
				
				List<Customer> cusList=daoSession.getCustomerDao().queryBuilder().where(
						CustomerDao.Properties.Name.eq(CUS_TEST)).list();
				for(Customer cus:cusList){
						cus.resetOrders();
						result.append("客户:"+cus.getName()+"的点击时间列表:\n");
						for(Order o:cus.getOrders()){
							result.append(o.getDate()+"\n");
						}
					}
					
			}
		});
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	public void initDao(){
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(getApplicationContext(),DB_NAME , null);
		SQLiteDatabase db = helper.getWritableDatabase();  
		DaoMaster daoMaster = new DaoMaster(db);  
		daoSession = daoMaster.newSession();  
		noteDao = daoSession.getNoteDao();  
		orderDao=daoSession.getOrderDao();
		cusDao=daoSession.getCustomerDao();
		
	}

}
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:scrollbars="@null">
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="insert "
        android:id="@+id/btnInsert"/>
    <Button
        android:layout_below="@+id/btnInsert"
        android:id="@+id/btnInsertOneToMany"
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="insertOneToMany">
    </Button>
    
    <TextView
        android:id="@+id/tvShow"
        android:layout_below="@+id/btnInsertOneToMany"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="@string/hello_world" />
</RelativeLayout>
</ScrollView>

PS: model中的user没能生成成功"Jsonable<User>" 接口没生成,我直接删掉了,没用

freemark.jar直接网上百度下就好,greendao.jar ,greendao-generator.jar在官网下载就行了 http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22de.greenrobot%22%20AND%20a%3A%22greendao%22  

还有,一对多查询时, 多的对象通常会取之前的缓存, cus.resetOrders();//
greendao-generator.jar就是一个自动生成dao和model的工具,和hibernate note有点类似。。

这个框架真不错,当你看到哗啦啦dao model都生成了,太快了,听说性能优化的也很好。所以赶紧用起来。是不是写的很简单?学的时候看各种博客看得吐血,作为菜鸟我只要简单粗暴的怎么用,至于他的怎么好怎么屌慢慢看嘛。你给我分析一大推,真正怎么用写得模糊。看得晕头转向云里雾里最后很可能现烦就放弃了,错过多么好的东西。

相关推荐