GreenDao3.2 uses detailed (add, delete, change, upgrade)

First look at renderings:

 

Project structure as shown below:

 

The first step: add build the configuration is as follows:

build.gradle directory under the projet

dependencies {

classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
}

Add under build.gradle moudle following:
Apply plugin: 'org.greenrobot.greendao'

Dependencies {
.....................

the compile 'org.greenrobot: greendao : 3.2.0 '
}


After the addition is complete click sync works

 


Step two:

First, add the following configuration in the root directory of build.gradle moudle

{greendao
// Schema version of the database, the database may be appreciated that the version number is
schemaVersion. 1
// set DaoMaster, DaoSession, Dao package name, the full path is disposed to package these classes.
daoPackage 'com.koimy.greedaotest.dao'
// set DaoMaster, DaoSession, Dao directory
targetGenDir 'the src / main / Java'
}
Add Student entity classes which project follows:
@Entity
public class Student {
@Id
Private Long ID ;
Private String name;
Private int Age;
Private String NUM;
}
In this case project directory as follows:


Then click on the android studio of build -> make project

At this time, items following structure:

 

Dao directory where the file is automatically generated by the greendao, Student occurred inside the content class are numbered as follows:

/**
* Created by hp on 2018/1/23.
*/
@Entity
public class Student {
@Id
private Long id;
private String name;
private int age;
private String num;
@Generated(hash = 1538557423)
public Student(Long id, String name, int age, String num) {
this.id = id;
this.name = name;
this.age = age;
this.num = num;
}
@Generated(hash = 1556870573)
public Student() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
void the setName public (String name) {
this.name = name;
}
public int getAge () {
return this.age;
}
public void the setAge (int Age) {
this.age = Age;
}
public String getNum () {
return the this .num;
}
public void setNum (String NUM) {
this.num NUM =;
}
GreenDao help us to automatically generate a number of get and set methods, and constructors
third step: for convenience we add a package db

 

DbManager classes are as follows:

package com.koimy.greedaotest.db;

/**
* Created by hp on 2018/1/23.
*/

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.koimy.greedaotest.dao.DaoMaster;
import com.koimy.greedaotest.dao.DaoSession;


public class DbManager {

// 是否加密
public static final boolean ENCRYPTED = true;

private static final String DB_NAME = "test.db";
private static DbManager mDbManager;
private static DaoMaster.DevOpenHelper mDevOpenHelper;
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;

private Context mContext;

private DbManager(Context context) {
this.mContext = context;
// 初始化数据库信息
mDevOpenHelper = new DaoMaster.DevOpenHelper(context, DB_NAME);
getDaoMaster(context);
getDaoSession(context);
}

public static DbManager getInstance(Context context) {
if (null == mDbManager) {
synchronized (DbManager.class) {
if (null == mDbManager) {
mDbManager = new DbManager(context);
}
}
}
return mDbManager;
}

/**
* 获取可读数据库
*
* @param context
* @return
*/
public static SQLiteDatabase getReadableDatabase(Context context) {
if (null == mDevOpenHelper) {
getInstance(context);
}
return mDevOpenHelper.getReadableDatabase();
}

/**
* 获取可写数据库
*
* @param context
* @return
*/
public static SQLiteDatabase getWritableDatabase(Context context) {
if (null == mDevOpenHelper) {
getInstance(context);
}

return mDevOpenHelper.getWritableDatabase();
}

/**
* 获取DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
if (null == mDaoMaster) {
synchronized (DbManager.class) {
if (null == mDaoMaster) {
mDaoMaster = new DaoMaster(getWritableDatabase(context));
}
}
}
Return mDaoMaster;
}

// / **
// * get DaoMaster
// *
// * determine whether there is a database, if not then create a database
// * @param context
// @return *
// * /
// public DaoMaster getDaoMaster static (the context context) {
// IF (mDaoMaster == null) {
// the synchronized (DbManager.class) {
// IF (mDaoMaster == null) {
// new new MyOpenHelper MyOpenHelper Helper = (context, the DB_NAME, null );
// mDaoMaster = new new DaoMaster (helper.getWritableDatabase ());
//}
//}
//}
// return mDaoMaster;
//}

/ **
* Get DaoSession
*
* @param context
* @return
* /
public static DaoSession getDaoSession(Context context) {
if (null == mDaoSession) {
synchronized (DbManager.class) {
mDaoSession = getDaoMaster(context).newSession();
}
}
return mDaoSession;
}
}
SutdentDaoOpe类如下:
package com.koimy.greedaotest.db;

/**
* Created by hp on 2018/1/23.
*/

import android.content.Context;


import com.koimy.greedaotest.dao.StudentDao;
import com.koimy.greedaotest.entity.Student;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;


public class StudentDaoOpe {

/**
* 添加数据至数据库
*
* @param context
@Param STU *
* /
public static void The insertData (the Context context, Student STU) {
DbManager.getDaoSession (context) .getStudentDao () INSERT (STU);.
}


/ **
* by adding the entity data transaction to the database
*
* @ context param
* @param List
* /
public static void The insertData (the context context, List <Student> List) {
IF (== null || list.size List () <= 0) {
return;
}
DbManager.getDaoSession (context) .getStudentDao () insertInTx (List);.
}

/ **
* add data to the database, if present, the original data covered
*, if present, the internal code is determined to update (entity); it does not exist INSERT (Entity);
*
@param context *
* @param Student
* /
static void the saveData public (the Context context, Student Student) {
DbManager.getDaoSession (context) .getStudentDao () Save (Student);.
}

/ **
* delete data to the database
*
* @param context
* @param Student delete the specific content
* /
public static void The deleteData (the context context, Student Student) {
DbManager.getDaoSession (context) .getStudentDao () delete (Student);.
}

/ **
* delete data to the database based on the id
*
* @param context
* @param id deleted specific contents
* /
public static void deleteByKeyData (the context context, Long ID) {
DbManager.getDaoSession (context) .getStudentDao () deleteByKey (ID);.
}

/ **
* delete all data
*
* @param context
*/
public static void deleteAllData(Context context) {
DbManager.getDaoSession(context).getStudentDao().deleteAll();
}

/**
* 更新数据库
*
* @param context
* @param student
*/
public static void updateData(Context context, Student student) {
DbManager.getDaoSession(context).getStudentDao().update(student);
}


/**
* 查询所有数据
*
* @param context
* @return
*/
public static List<Student> queryAll(Context context) {
QueryBuilder<Student> builder = DbManager.getDaoSession(context).getStudentDao().queryBuilder();

return builder.build().list();
}



/ **
* tab loading
* @param context
* @param pageSize Current pages (program to dynamically modify the value of pageSize)
* @param pageNum shows how many page
* @return
* /
public static List <Student> queryPaging (the pageSize int, int pageNum, the context context) {
StudentDAO StudentDAO = DbManager.getDaoSession (context) .getStudentDao ();
List <Student> listMsg = studentDao.queryBuilder ()
.offset (pageNum the pageSize *) .limit (pageNum). List ();
return listMsg;
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.koimy.demo2.MainActivity">


<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="增" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="删" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="改" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查" />

<LinearLayout
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/btn_query_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="根据ID查询(分页查询)" />

<Button
android:id="@+id/button5"
android:layout_width="107dp"
android:layout_height="wrap_content"
android:text="删除全部" />
</LinearLayout>

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>

</LinearLayout>

MainActivithy.java
package com.koimy.greedaotest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.koimy.greedaotest.db.StudentDaoOpe;
import com.koimy.greedaotest.entity.Student;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

@BindView(R.id.button)
Button button;
@BindView(R.id.button2)
Button button2;
@BindView(R.id.button3)
Button button3;
@BindView(R.id.button4)
Button button4;
@BindView(R.id.btn_query_all)
Button btnQueryAll;
@BindView(R.id.button5)
Button button5;
@BindView(R.id.tv_content)
TextView tvContent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initData();
}

private List<Student> studentList = new ArrayList<>();

/**
* 初始化数据
*/
private void initData() {
for (int i = 0; i < 100; i++) {
Student student = new Student((long) i, "huang" + i, 25,"666"+i);
studentList.add(student);
}

}

int page;

@OnClick({R.id.button, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.btn_query_all})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button:
StudentDaoOpe.insertData(this, studentList);
break;
case R.id.button2:
Student student = new Student((long) 5, "haung" + 5, 25,"123456");
/**
* 根据特定的对象删除
*/
StudentDaoOpe.deleteData(this, student);
/**
* 根据主键删除
*/
StudentDaoOpe.deleteByKeyData(this, 7);
StudentDaoOpe.deleteAllData(this);
break;
case R.id.button3:
student = new Student((long) 2, "caojin", 1314,"888888");
StudentDaoOpe.updateData(this, student);
break;
case R.id.button4:
List<Student> students = StudentDaoOpe.queryAll(this);
tvContent.setText(students.toString());
for (int i = 0; i < students.size(); i++) {
Log.i("Log", students.get(i).getName());
}

break;
case R.id.button5:
StudentDaoOpe.deleteAllData(this);
break;
case R.id.btn_query_all:
List<Student> students2 = StudentDaoOpe.queryPaging(page, 20, this);

if (students2.size() == 0) {
Toast.makeText (this, "a no more data", Toast.LENGTH_SHORT) the .Show ();
}
for (Student ST: students2) {
Log.e ( "the TAG", "onViewClicked: ==" + ST);
Log.e ( "the TAG", "onViewClicked: == NUM =" + st.getNum ());
}
Page ++;
tvContent.setText (students2.toString ());
BREAK;
}
}


}
finally / data / data / package name / databases / database name / table name generation table structure is shown below:

 

Here to talk about upgrading the database:

First, the introduction of a new package two helper classes, as follows:

MigrationHelper categories:


com.koimy.greedaotest.helper Package Penalty for;

/ **
* Update the database helper class
*
* principle: to create a temporary table -> delete the original table -> Create New Table -> Copy temporary table data to a new table and delete temporary table ; update such database table is complete
* /

Import android.database.Cursor;
Import android.text.TextUtils;
Import android.util.Log;


Import com.koimy.greedaotest.dao.DaoMaster;

Import org.greenrobot.greendao. AbstractDao.;
Import org.greenrobot.greendao.database.Database;
Import org.greenrobot.greendao.internal.DaoConfig;

Import of 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 DOES NOT 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);
}

/**
* 生成临时列表
*
* @param db
* @param 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<String> 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) {
exception.printStackTrace();
}

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

}
}

/**
* 存储新的数据库表 以及数据
*
* @param db
* @param daoClasses
*/
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<String> 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()));
exception.printStackTrace();
throw exception;
}

private List<String> getColumns(Database db, String tableName) {
List<String> 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;
}
}
MyOpenHelper类:

package com.koimy.greedaotest.helper;

/**
* Created by hp on 2018/1/23.
*/

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


import com.koimy.greedaotest.dao.DaoMaster;
import com.koimy.greedaotest.dao.StudentDao;

import org.greenrobot.greendao.database.Database;


public class MyOpenHelper extends DaoMaster.OpenHelper {

public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}

/**
* 数据库升级
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
void onUpgrade public (Database db, oldVersion int, int newVersion) {
// update the database operating table a few upgrades can be passed to the following

Log.i ( "version", oldVersion + "--- before and after update version --- "+ newVersion);
IF (oldVersion <newVersion) {
Log.i (" version ", oldVersion +" --- previous version after update and --- "+ newVersion);
MigrationHelper.getInstance (). the migrate (db, StudentDao.class);
// changed entity class (do not add new) UserDao update file can add multiple XXDao.class file
. // MigrationHelper.getInstance () migrate (db , UserDao.class, XXDao.class);
}



//MigrationHelper.getInstance().migrate(db,StudentDao.class);
}

}
then
/ **
* Get DaoMaster
*
* @param context
* @return
* /
public static DaoMaster getDaoMaster(Context context) {
if (null == mDaoMaster) {
synchronized (DbManager.class) {
if (null == mDaoMaster) {
mDaoMaster = new DaoMaster(getWritableDatabase(context));
}
}
}
return mDaoMaster;
}
换成如下所示:

/ **
* Get DaoMaster
*
* determined whether there is a database, the database is created if no
* @param context
* @return
* /
public static DaoMaster getDaoMaster (the Context context) {
IF (mDaoMaster == null) {
the synchronized (DbManager.class) {
IF (mDaoMaster == null) {
MyOpenHelper Helper MyOpenHelper = new new (context, the DB_NAME, null);
mDaoMaster = new new DaoMaster (helper.getWritableDatabase ());
}
}
}
return mDaoMaster;
}
Next: which we add the class Student a grade property attribute, then to 2 build.gradle inside schemaVersion

 

Then compiled, run the program, then we will look at the upgraded database, as shown successfully added me what the new field, but also retains the previous data

 



Guess you like

Origin www.cnblogs.com/aibabel/p/11311703.html