greendao3.0以上使用步骤(二):数据库到底该怎么升级
- 引入数据库
1、在项目的build.gradle中加入这些配置
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
记得加上
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
2、在mould的build.gradle中加入这些配置
apply plugin: 'org.greenrobot.greendao'
greendao {
//数据库的schema版本,也可以理解为数据库版本号
schemaVersion 1
//设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。
daoPackage 'com.yintong.secure.simple.encryptiongreendao.greendao'
//设置DaoMaster、DaoSession、Dao目录
targetGenDir 'src/main/java'
}
dependencies {
compile 'org.greenrobot:greendao:3.2.2'
compile 'net.zetetic:android-database-sqlcipher:3.5.1'
}
- 创建Student实体类
package com.yintong.secure.simple.encryptiongreendao.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Keep;
import org.greenrobot.greendao.annotation.Generated;
@Entity(generateConstructors = false)
public class Student {
@Id
private Long id;
private String name;
private int age;
public Student() {
}
@Keep
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(Long id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Keep
public Long getId() {
return id;
}
@Keep
public void setId(Long id) {
this.id = id;
}
@Keep
public String getName() {
return name;
}
@Keep
public void setName(String name) {
this.name = name;
}
@Keep
public int getAge() {
return age;
}
@Keep
public void setAge(int age) {
this.age = age;
}
@Keep
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return name.equals(student.name);
}
@Keep
@Override
public int hashCode() {
return (int) (id ^ (id >>> 32));
}
@Keep
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
修复一下工程,自动生成greendao包下的类(就是点击一下小锤子),你会自动生成上图中greendao包中的类。
开始使用,创建管理类
package com.yintong.secure.simple.encryptiongreendao.dao;
import android.content.Context;
import com.yintong.secure.simple.encryptiongreendao.greendao.DaoMaster;
import com.yintong.secure.simple.encryptiongreendao.greendao.DaoSession;
import org.greenrobot.greendao.database.Database;
public class DbManager {
// 是否加密
public static final boolean ENCRYPTED = true;
private static DbManager mDbManager;
private static DaoMaster.DevOpenHelper mDevOpenHelper;
private static DaoMaster mDaoMaster;
private static DaoSession mDaoSession;
private DbManager(Context context, String dbName, String passwprd) {
// 初始化数据库信息
mDevOpenHelper = new DaoMaster.DevOpenHelper(context, dbName);
getDaoMaster(context, dbName, passwprd);
getDaoSession(context, dbName, passwprd);
}
public static DbManager getInstance(Context context, String dbName, String passwprd) {
if (null == mDbManager) {
synchronized (DbManager.class) {
if (null == mDbManager) {
mDbManager = new DbManager(context, dbName, passwprd);
}
}
}
return mDbManager;
}
/**
* 获取可读数据库
*
* @param context
* @return
*/
public static Database getReadableDatabase(Context context, String dbName, String passwprd) {
if (null == mDevOpenHelper) {
getInstance(context, dbName, passwprd);
}
if (ENCRYPTED) {//加密
return mDevOpenHelper.getEncryptedReadableDb(passwprd);
} else {
return mDevOpenHelper.getReadableDb();
}
}
/**
* 获取可写数据库
*
* @param context
* @param dbName
* @param passwprd
* @return
*/
public static Database getWritableDatabase(Context context, String dbName, String passwprd) {
if (null == mDevOpenHelper) {
getInstance(context, dbName, passwprd);
}
if (ENCRYPTED) {//加密
return mDevOpenHelper.getEncryptedWritableDb(passwprd);
} else {
return mDevOpenHelper.getWritableDb();
}
}
/**
* 获取DaoMaster
*
* @param context
* @param dbName
* @param passwprd
* @return
*/
public static DaoMaster getDaoMaster(Context context, String dbName, String passwprd) {
if (null == mDaoMaster) {
synchronized (DbManager.class) {
if (null == mDaoMaster) {
mDaoMaster = new DaoMaster(getWritableDatabase(context, dbName, passwprd));
}
}
}
return mDaoMaster;
}
/**
* 获取DaoSession
*
* @param context
* @param dbName
* @param passwprd
* @return
*/
public static DaoSession getDaoSession(Context context, String dbName, String passwprd) {
if (null == mDaoSession) {
synchronized (DbManager.class) {
// mDaoSession = getDaoMaster(context,dbName,passwprd).newSession();
mDaoSession = getDaoMaster(context, dbName, passwprd).newDevSession(context, dbName);
}
}
return mDaoSession;
}
}
- 增删改查
package com.yintong.secure.simple.encryptiongreendao.dao;
import android.content.Context;
import com.yintong.secure.simple.encryptiongreendao.bean.Student;
import com.yintong.secure.simple.encryptiongreendao.greendao.StudentDao;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
public class StudentDaoOpe {
private static final String DB_NAME = "test.db";
private static final String PASSWPRD = "password";
/**
* 添加数据至数据库
*
* @param context
* @param stu
*/
public static void insertData(Context context, Student stu) {
// DbManager.getDaoSession(context, DB_NAME,PASSWPRD).getStudentDao().insert(stu);
DbManager.getDaoSession(context, DB_NAME,PASSWPRD).getStudentDao().insertOrReplace(stu);
}
/**
* 将数据实体通过事务添加至数据库
*
* @param context
* @param list
*/
public static void insertData(Context context, List<Student> list) {
if (null == list || list.size() <= 0) {
return;
}
// DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().insertInTx(list);
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().insertOrReplaceInTx(list);
}
/**
* 添加数据至数据库,如果存在,将原来的数据覆盖
* 内部代码判断了如果存在就update(entity);不存在就insert(entity);
*
* @param context
* @param student
*/
public static void saveData(Context context, Student student) {
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().save(student);
}
/**
* 删除数据至数据库
*
* @param context
* @param student 删除具体内容
*/
public static void deleteData(Context context, Student student) {
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().delete(student);
}
/**
* 根据id删除数据至数据库
*
* @param context
* @param id 删除具体内容
*/
public static void deleteByKeyData(Context context, long id) {
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().deleteByKey(id);
}
/**
* 删除全部数据
*
* @param context
*/
public static void deleteAllData(Context context) {
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().deleteAll();
}
/**
* 更新数据库
*
* @param context
* @param student
*/
public static void updateData(Context context, Student student) {
DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().update(student);
}
/**
* 查询所有数据
*
* @param context
* @return
*/
public static List<Student> queryAll(Context context) {
QueryBuilder<Student> builder = DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().queryBuilder();
return builder.build().list();
}
/**
* 根据id,其他的字段类似
*
* @param context
* @param id
* @return
*/
public static List<Student> queryForId(Context context, long id) {
QueryBuilder<Student> builder = DbManager.getDaoSession(context, DB_NAME, PASSWPRD).getStudentDao().queryBuilder();
/**
* 返回当前id的数据集合,当然where(这里面可以有多组,做为条件);
* 这里build.list();与where(StudentDao.Properties.Id.eq(id)).list()结果是一样的;
* 在QueryBuilder类中list()方法return build().list();
*
*/
// Query<Student> build = builder.where(StudentDao.Properties.Id.eq(id)).build();
// List<Student> list = build.list();
return builder.where(StudentDao.Properties.Id.eq(id)).list();
}
}
- mainactivity布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="增" />
<Button
android:id="@+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删" />
<Button
android:id="@+id/updata"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="改" />
<Button
android:id="@+id/check"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="查" />
</LinearLayout>
<Button
android:id="@+id/deleteAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_weight="1"
android:text="删除全部" />
<Button
android:id="@+id/check_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/deleteAll"
android:layout_centerInParent="true"
android:text="根据id查" />
</RelativeLayout>
- mainActivity
package com.yintong.secure.simple.encryptiongreendao;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.yintong.secure.simple.encryptiongreendao.bean.Student;
import com.yintong.secure.simple.encryptiongreendao.dao.StudentDaoOpe;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.add)
Button add;
@Bind(R.id.delete)
Button delete;
@Bind(R.id.updata)
Button updata;
@Bind(R.id.check)
Button check;
@Bind(R.id.deleteAll)
Button deleteAll;
@Bind(R.id.check_id)
Button checkId;
private Context mContext;
private Student student;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mContext = this;
initData();
initListener();
}
private List<Student> studentList = new ArrayList<>();
/**
* 初始化数据
*/
private void initData() {
for (int i = 0; i < 100; i++) {
student = new Student((long) i, "huang" + i, 25);
studentList.add(student);
}
}
private void initListener() {
/**
*增
*/
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StudentDaoOpe.insertData(mContext, studentList);
}
});
/**
* 删
*/
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Student student = new Student((long) 5, "haung" + 5, 25);
/**
* 根据特定的对象删除
*/
StudentDaoOpe.deleteData(mContext, student);
/**
* 根据主键删除
*/
StudentDaoOpe.deleteByKeyData(mContext, 7);
}
});
/**
*删除所有
*/
deleteAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StudentDaoOpe.deleteAllData(mContext);
}
});
/**
* 更新
*/
updata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Student student = new Student((long) 2, "haungxiaoguo", 16516);
StudentDaoOpe.updateData(mContext, student);
}
});
/**
* 查询全部
*/
check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Student> students = StudentDaoOpe.queryAll(mContext);
for (int i = 0; i < students.size(); i++) {
Log.i("Log", students.get(i).getName());
}
}
});
/**
* 根据id查询
*/
checkId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Student> students = StudentDaoOpe.queryForId(mContext, 50);
for (int i = 0; i < students.size(); i++) {
Log.i("Log", students.get(i).getName());
}
}
});
}
}