高效的GreenDao 数据库操作框架应用

一、greenDao的简单介绍

      最近理解设计模式有点累,转接来了解下开发框架。笔者对于数据库操作一直觉得觉得很繁琐,代码量太多,自己通过原生方式构建数据库,对数据的增删改查,效率不说,操作起来也是挺费劲的。这几天了解下数据库框架,发现一个性能较强大的数据库框架greenDAO,这里我引用官方网站一张与ORMlite框架的性能图。



由效能对比图可以看出来,无论是插入、更新、还是数据库读取吞吐量,都大大超过 ORMlite框架,碉堡了!!!

greenDAO开发框架也是基于ORM框架形成的,这里对于框架的应用主要通过中介greenDao,将java bean实体类与sqlite进行数据操作桥梁,即简化了sqlite操作!下图所示即为 greenDAO通信机制。



二、greenDao的使用

greenDao使用相对 ORMlite而言, ORMlite比较简单操作,而 greenDao需要创建一个依赖java工程,通过编译运行java工程生成DaoMaster、DaoSession等类(笔者第一次搞的时候遇到好多坑。。),但是相对来说 greenDao还是较为高效的,不多说,直接进入使用教程,这里是以Android Studio开发环境作为解说。

1.在 android studio 环境创建java工程

首先是New->Module,选择java library,进入创建界面如下


命名自己喜欢


然后在创建的module的bulid.gradle中添加greenDAO支持包,如下所示:
   
   
apply plugin: 'java'
 
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'de.greenrobot:greendao-generator:2.0.0'
 
}
以上就简单配置了java工程,下面进入第2个步骤。

2.创建java工程main函数,执行自动创建以来java类

    
    
public class AppMyGenerator {
 
public static void main(String[] args) throws Exception {
Schema schema = new Schema(1, "cn.wsy.commom.bean");//创建一个操作Schema操作对象,这里两个形参意思是代表数据库版本号与数据表字段存储的对象包名
schema.setDefaultJavaPackageDao("cn.wsy.commom.dao");//这里是指定自动生成的数据表操作类包名
schema.enableActiveEntitiesByDefault();
schema.enableKeepSectionsByDefault();
initUserBean(schema);//初始化数据表字段
new DaoGenerator().generateAll(schema, "app/src/main/java");//指定存储的工作路径
}
 
private static void initUserBean(Schema schema) {
Entity userBean = schema.addEntity("UserBean");
userBean.setTableName("user");//表名字
userBean.addStringProperty("id").primaryKey().index();//字段,并且为主键
userBean.addStringProperty("phone");
userBean.addStringProperty("gender");
}
 
}
创建完后,在android studio里面运行Java工程即可自动生成操作类,如下图所示。


看到app/src/main/java 路径下面是否已经生成了操作类


这里简单解释下这两个包名的作用
    
    
package cn.wsy.commom.bean;
 
import cn.wsy.commom.dao.DaoSession;
import de.greenrobot.dao.DaoException;
 
import cn.wsy.commom.dao.UserBeanDao;
 
// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS
 
// KEEP INCLUDES - put your custom includes here
// KEEP INCLUDES END
/**
* Entity mapped to table "user".
*/
public class UserBean {
 
private String id;
private String phone;
private String profile_picture;
private String client_id;
private String name;
private String location;
private String gender;
 
/** Used to resolve relations */
private transient DaoSession daoSession;
 
/** Used for active entity operations. */
private transient UserBeanDao myDao;
 
 
// KEEP FIELDS - put your custom fields here
// KEEP FIELDS END
 
public UserBean() {
}
 
public UserBean(String id) {
this.id = id;
}
 
public UserBean(String id, String phone, String profile_picture, String client_id, String name, String location, String gender) {
this.id = id;
this.phone = phone;
this.profile_picture = profile_picture;
this.client_id = client_id;
this.name = name;
this.location = location;
this.gender = gender;
}
 
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getUserBeanDao() : null;
}
 
public String getId() {
return id;
}
 
public void setId(String id) {
this.id = id;
}
 
public String getPhone() {
return phone;
}
 
public void setPhone(String phone) {
this.phone = phone;
}
 
public String getProfile_picture() {
return profile_picture;
}
 
public void setProfile_picture(String profile_picture) {
this.profile_picture = profile_picture;
}
 
public String getClient_id() {
return client_id;
}
 
public void setClient_id(String client_id) {
this.client_id = client_id;
}
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public String getLocation() {
return location;
}
 
public void setLocation(String location) {
this.location = location;
}
 
public String getGender() {
return gender;
}
 
public void setGender(String gender) {
this.gender = gender;
}
 
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
 
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
 
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
 
// KEEP METHODS - put your custom methods here
// KEEP METHODS END
 
}
这里自动生成的UserBean.java类,其实就是简单的实体类,包括所有数据表中创建的字段。
     
     
package cn.wsy.commom.dao;
 
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
 
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
 
import cn.wsy.commom.bean.UserBean;
 
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "user".
*/
public class UserBeanDao extends AbstractDao<UserBean, String> {
 
public static final String TABLENAME = "user";
 
/**
* Properties of entity UserBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, String.class, "id", true, "ID");
public final static Property Phone = new Property(1, String.class, "phone", false, "PHONE");
public final static Property Profile_picture = new Property(2, String.class, "profile_picture", false, "PROFILE_PICTURE");
public final static Property Client_id = new Property(3, String.class, "client_id", false, "CLIENT_ID");
public final static Property Name = new Property(4, String.class, "name", false, "NAME");
public final static Property Location = new Property(5, String.class, "location", false, "LOCATION");
public final static Property Gender = new Property(6, String.class, "gender", false, "GENDER");
};
 
private DaoSession daoSession;
 
 
public UserBeanDao(DaoConfig config) {
super(config);
}
public UserBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
this.daoSession = daoSession;
}
 
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"user\" (" + //
"\"ID\" TEXT PRIMARY KEY NOT NULL ," + // 0: id
"\"PHONE\" TEXT," + // 1: phone
"\"PROFILE_PICTURE\" TEXT," + // 2: profile_picture
"\"CLIENT_ID\" TEXT," + // 3: client_id
"\"NAME\" TEXT," + // 4: name
"\"LOCATION\" TEXT," + // 5: location
"\"GENDER\" TEXT);"); // 6: gender
// Add Indexes
db.execSQL("CREATE INDEX " + constraint + "IDX_user_ID ON user" +
" (\"ID\");");
}
 
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"user\"";
db.execSQL(sql);
}
 
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, UserBean entity) {
stmt.clearBindings();
String id = entity.getId();
if (id != null) {
stmt.bindString(1, id);
}
String phone = entity.getPhone();
if (phone != null) {
stmt.bindString(2, phone);
}
String profile_picture = entity.getProfile_picture();
if (profile_picture != null) {
stmt.bindString(3, profile_picture);
}
String client_id = entity.getClient_id();
if (client_id != null) {
stmt.bindString(4, client_id);
}
String name = entity.getName();
if (name != null) {
stmt.bindString(5, name);
}
String location = entity.getLocation();
if (location != null) {
stmt.bindString(6, location);
}
String gender = entity.getGender();
if (gender != null) {
stmt.bindString(7, gender);
}
}
 
@Override
protected void attachEntity(UserBean entity) {
super.attachEntity(entity);
entity.__setDaoSession(daoSession);
}
 
/** @inheritdoc */
@Override
public String readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0);
}
 
/** @inheritdoc */
@Override
public UserBean readEntity(Cursor cursor, int offset) {
UserBean entity = new UserBean( //
cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // phone
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // profile_picture
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // client_id
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // name
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // location
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6) // gender
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, UserBean entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0));
entity.setPhone(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setProfile_picture(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setClient_id(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setName(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setLocation(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setGender(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
}
/** @inheritdoc */
@Override
protected String updateKeyAfterInsert(UserBean entity, long rowId) {
return entity.getId();
}
/** @inheritdoc */
@Override
public String getKey(UserBean entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
 
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
这里首先这个类继承了 AbstractDao类,我们在这个类里面很简单可以看到 delete、insert、query等等数据库常见的操作方法,对greenDao执行的main函数帮你自动生成了所有数据库操作的方法!

3.android 测试
使用之前记得引入greenDao支持jar,与上面java工程的jar不一样的(笔者就被坑了。。 ),如下所示:
    
    
compile 'de.greenrobot:greendao:2.1.0'
简单测试下插入:
    
    
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "wsy-db", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
UserBeanDao userDao = daoSession.getUserBeanDao();
userDao.insert(new UserBean("1","1","1","1","1","1","1"));
这里说明下:我们虽然已经自动生成操作框架,但是在这类的时候我们依然还没有生成应用数据库,这里也不需要我们写“create tab...”等sql语句去执行生成,直接实现DaoMaster的子类DevOpenHelper即可,如下
    
    
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "wsy-db", null);
剩下的就是通过获取数据库操作对象 SQLiteDatabase 对象,将该对象注入到 DaoMaster 对象中获取指定操作表的操作对象例如UserBeanDao对象,即为数据表“uer”操作对象,也许很多读者会提出 DaoSession 有什么作用,这里大概你能够理解成控制管理所有数据表操作对象的工厂提供类,即你需要什么数据表操作对象只需要get即可。
    
    
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();
UserBeanDao userDao = daoSession.getUserBeanDao();
最后就是直接操作数据表操作对象,直接对数据进行增删改查了!!!如下:
    
    
userDao.insert(new UserBean("1","1","1","1","1","1","1"));//插入数据
     
     
List<UserBean> data = userDao.queryRaw(" where id='1'", null);//查找整行数据



具体数据库操作方法请参考greenDAO API文档,笔者下期详细在解释。


傻小孩b
20160226
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值