1、首先需要引入到工程中,在as中导入相关的jar,
compile 'org.greenrobot:greendao:3.0.1'
compile 'org.greenrobot:greendao-generator:3.0.0'
2、在app的build.gradle文件中声明greendao的路径、版本、名称的设置
greendao {
/**
* 版本号
*/
schemaVersion 1
/**
* greendao输出dao的数据库操作实体类文件夹(相对路径 包名+自定义路径名称,包将创建于包名的直接路径下)
*/
daoPackage 'com.qiufeng.greendao.greendao.gen'
/**
* greenDao实体类包文件夹
*/
targetGenDir 'src/main/java'
}
3、在project的build.gradle中添加代码,apply plugin 的声明可以放到app的 build.gradle中
apply plugin: 'org.greenrobot.greendao'
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0'
}
}
4、创建实体类,以@Entity注解标注,其中需添加id列,类型必须为Long类型,为其索引,如下:
/**
* 用户信息
* Created by 秋风 on 2016/10/12.
*/
@Entity
public class UserInfo {
@Id
private Long id;
/**
* 用户名
*/
private String userName;
/**
* 别名
*/
private String nickName;
/**
* 密码
*/
private String password;
/**
* 年龄
*/
private int age;
/**
* 卡号
*/
private String card;
/**
* 性别
*/
private String gender;
}
5、创建完成实体类之后点击Build–>MarkProject,会自动在配置的路径下生成DaoMaster、DaoSession、以及UserInfoDao文件(如果拥有多个实体类,则会生成多个实体类Dao文件),并且,刚才编写的实体类文件UserInfo会自动生成get、set方法跟无参构造以及完整参数的构造方法
6、目前测试前的环境基本搭建完成了,下面就开始进行测试,首先初始化我们的设置,在Application中
public class App extends Application {
private DaoMaster.DevOpenHelper dbHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static App instance;
@Override
public void onCreate() {
super.onCreate();
init();
initDatabass();
}
public static App getInstance(){
return instance;
}
private void initDatabass() {
//这里之后会修改,关于升级数据库
dbHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = dbHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getSession(){
return mDaoSession;
}
public SQLiteDatabase getDb(){
return db;
}
private void init() {
instance = this;
}
}
7、使用GreenDao3.0的功能,只需要声明我们要操作的Dao,然后进行使用就好,这里就不一一介绍了,统一贴出代码
package com.qiufeng.greendao;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.qiufeng.greendao.application.App;
import com.qiufeng.greendao.entity.UserInfo;
import com.qiufeng.greendao.greendao.gen.UserInfoDao;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private UserInfoDao dao;
private TextView id_userinfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
dao = App.getInstance().getSession().getUserInfoDao();
// dao.deleteAll();
// insert();
update();
select();
}
/**
* 修改
*/
private void update() {
//通过多种方式获取实例
// UserInfo userInfo = dao.queryBuilder().where(UserInfoDao.Properties.UserName.eq("qiufeng4")).build().unique();
UserInfo userInfo = dao.load((long)1);
if (userInfo != null) {
userInfo.setNickName("秋风哈哈");
dao.update(userInfo);
Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
}
}
/**
* 初始化视图组件
*/
private void initView() {
id_userinfo = (TextView) findViewById(R.id.id_userinfo);
}
/**
* 查询
*/
private void select() {
List userInfos = dao.loadAll();
if (userInfos == null) {
return;
}
UserInfo userInfo = userInfos.get(userInfos.size() - 1);
Log.e("qiufeng", "select: " + userInfos.size());
id_userinfo.setText("ID:" + userInfo.getId()
+ "\n userName:" + userInfo.getUserName()
+ "\n nichName:" + userInfo.getNickName()
+ "\n age:" + userInfo.getAge() + "card:"
+ userInfo.getCard() + "\n gender:"
+ userInfo.getGender());
}
/**
* 数据库添加信息
*/
private void insert() {
UserInfo userInfo = new UserInfo(null, "qiufeng4", "junyou4", "444444", 28, "3700000000000004", "男");
dao.insert(userInfo);
}
}
到这里基本的增删改查都可以完成,删除方法没有写,不过也是很简单,大家只要同过获取的dao实例“点”一下都能找到,框架的好处就是降低使用门槛跟减少繁琐的代码逻辑嘛,好吧贴图,其实跟修改差不多的条件,对象,或者是key(id)
8、数据库的升级,这个估计是很多人比较关注的,我也是从网上其他博贴中寻找的方法,当然是跟GreenDao匹配的了,建议直接粘贴,因为有几处其他的地方用的数据库类型不一致
package com.qiufeng.greendao.helper;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import com.qiufeng.greendao.greendao.gen.DaoMaster;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.internal.DaoConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 数据库升级
*/
public class MigrationHelper {
private static final String CONVERSION_CLASS_NOT_FOUND_EXCEPTION = "MIGRATION HELPER - CLASS DOESN'T MATCH WITH THE CURRENT PARAMETERS";
private static MigrationHelper instance;
public static MigrationHelper getInstance() {
if(instance == null) {
instance = new MigrationHelper();
}
return instance;
}
public void migrate(Database db, Class extends AbstractDao, ?>>... daoClasses) {
generateTempTables(db, daoClasses);
DaoMaster.dropAllTables(db, true);
DaoMaster.createAllTables(db, false);
restoreData(db, daoClasses);
}
private void generateTempTables(Database db, Class extends AbstractDao, ?>>... daoClasses) {
for(int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String divider = "";
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList properties = new ArrayList();
StringBuilder createTableStringBuilder = new StringBuilder();
createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" (");
for(int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if(getColumns(db, tableName).contains(columnName)) {
properties.add(columnName);
String type = null;
try {
type = getTypeByClass(daoConfig.properties[j].type);
} catch (Exception exception) {
}
createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);
if(daoConfig.properties[j].primaryKey) {
createTableStringBuilder.append(" PRIMARY KEY");
}
divider = ",";
}
}
createTableStringBuilder.append(");");
db.execSQL(createTableStringBuilder.toString());
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tableName).append(";");
db.execSQL(insertTableStringBuilder.toString());
}
}
private void restoreData(Database db, Class extends AbstractDao, ?>>... daoClasses) {
for(int i = 0; i < daoClasses.length; i++) {
DaoConfig daoConfig = new DaoConfig(db, daoClasses[i]);
String tableName = daoConfig.tablename;
String tempTableName = daoConfig.tablename.concat("_TEMP");
ArrayList properties = new ArrayList();
for (int j = 0; j < daoConfig.properties.length; j++) {
String columnName = daoConfig.properties[j].columnName;
if(getColumns(db, tempTableName).contains(columnName)) {
properties.add(columnName);
}
}
StringBuilder insertTableStringBuilder = new StringBuilder();
insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(") SELECT ");
insertTableStringBuilder.append(TextUtils.join(",", properties));
insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");
StringBuilder dropTableStringBuilder = new StringBuilder();
dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);
db.execSQL(insertTableStringBuilder.toString());
db.execSQL(dropTableStringBuilder.toString());
}
}
private String getTypeByClass(Class> type) throws Exception {
if(type.equals(String.class)) {
return "TEXT";
}
if(type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class)) {
return "INTEGER";
}
if(type.equals(Boolean.class)) {
return "BOOLEAN";
}
Exception exception = new Exception(CONVERSION_CLASS_NOT_FOUND_EXCEPTION.concat(" - Class: ").concat(type.toString()));
throw exception;
}
private static List getColumns(Database db, String tableName) {
List columns = new ArrayList();
Cursor cursor = null;
try {
cursor = db.rawQuery("SELECT * FROM " + tableName + " limit 1", null);
if (cursor != null) {
columns = new ArrayList(Arrays.asList(cursor.getColumnNames()));
}
} catch (Exception e) {
Log.v(tableName, e.getMessage(), e);
e.printStackTrace();
} finally {
if (cursor != null)
cursor.close();
}
return columns;
}
}
然后添加一个OpenHelper的帮助类,继承DaoMaster.OpenHelper,并重写onUpgrade方法
package com.qiufeng.greendao.helper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.qiufeng.greendao.greendao.gen.DaoMaster;
import com.qiufeng.greendao.greendao.gen.UserInfoDao;
import org.greenrobot.greendao.database.Database;
/**
* 自定义OpenHelper
*/
public class QFOpenHelper extends DaoMaster.OpenHelper {
public QFOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
/**
* 升级数据库
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
//操作数据库的更新
MigrationHelper.getInstance().migrate(db,UserInfoDao.class);
}
}
最后修改我们在application中的引用,将DaoMaster.DevOpenHelper修改为QFOpenHelper,
好吧,重新贴下代码
package com.qiufeng.greendao.application;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import com.qiufeng.greendao.greendao.gen.DaoMaster;
import com.qiufeng.greendao.greendao.gen.DaoSession;
import com.qiufeng.greendao.helper.QFOpenHelper;
/**
* Created by 秋风 on 2016/10/12.
*/
public class App extends Application {
private DaoMaster.DevOpenHelper dbHelper;
private QFOpenHelper helper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static App instance;
@Override
public void onCreate() {
super.onCreate();
init();
initDatabass();
}
public static App getInstance(){
return instance;
}
private void initDatabass() {
// dbHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
helper=new QFOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getSession(){
return mDaoSession;
}
public SQLiteDatabase getDb(){
return db;
}
/**
* 初始化App
*/
private void init() {
instance = this;
}
}
总结,没啥好说的,对于脑力不太够的我们,成长就需要多“跟风”,但凡是好的,即使不是最好的,但相比我们用的东西,子要是优于当前,就需要多查,多看,多了解
多谢费时浏览