【11】【3】【完結】Android GreenDao 增刪改查 實戰
阿新 • • 發佈:2018-12-11
我把這個demo 釋出到了git 上 我要去看看
需要可以去下載
我們需要對 greenDao做二次封裝 以便於使用
新建 dbmanager 檔案 裡面分別存放 CommonUtils DaoManager
DaoManager 有四個作用
/**
* 1 建立資料庫
* 2 建立資料庫的表
* 3 包含對資料庫的CRUD
* 4 對資料的升級
*/
CommonUtils
完成對某一張表的具體操作 ORM 操作的是物件 Student
再次強調一下 物件操作就是資料庫操作 而類名就是表名 所以表名為SUDENT
屬性名稱為欄位名稱
java-gen是用生成器生成的所以此處我就不再貼了
DaoManager
package com.boradcasst.liuan.greendaodemo.dbmanager; import android.content.Context; import com.student.dao.DaoMaster; import com.student.dao.DaoSession; import org.greenrobot.greendao.query.QueryBuilder; /** * 1 建立資料庫 * 2 建立資料庫的表 * 3 包含對資料庫的CRUD * 4 對資料的升級 */ public class DaoManager { private static final String TAG = "DbManager"; private static final String DB_NAME = "mydb.sqlite";//資料庫名稱 private volatile static DaoManager manager;//多執行緒訪問 private static DaoMaster.DevOpenHelper helper; private static DaoMaster daoMaster; private static DaoSession daoSession; private Context context; /** * 使用單例模式 獲得操作資料庫的物件 * @return */ public void init(Context context){ this.context=context; } public static DaoManager getInstance() { DaoManager instance = null; if (manager == null) { synchronized (DaoManager.class) { if (instance == null) { instance = new DaoManager(); manager = instance; } } } return instance; } /** * 判斷是否有存在資料庫 如果沒有則建立資料庫 * @return */ public DaoMaster getDaoMaster(){ if(daoMaster==null){ DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null); daoMaster=new DaoMaster(devOpenHelper.getWritableDatabase()); } return daoMaster; } /** * 完成對資料庫的新增 刪除 修改 查詢的操作 僅僅是一個介面 * @return */ public DaoSession getDaoSession(){ if (daoSession == null) { if (daoMaster == null) { daoMaster=getDaoMaster(); } daoSession=daoMaster.newSession(); } return daoSession; } /** * 開啟輸出日誌的操作,預設是關閉的 */ public void setDebug(){ QueryBuilder.LOG_SQL=true; QueryBuilder.LOG_VALUES=true; } public void closeDaoSession(){ if (daoSession != null) { daoSession.clear(); daoSession=null; } } public void closeHelper(){ if (helper != null) { helper.close(); helper=null; } } /** * 關閉所有的操作,資料庫開啟的時候,使用完畢了必須關閉 */ public void closeConnection(){ closeHelper(); closeDaoSession(); } }
CommonUtils
package com.boradcasst.liuan.greendaodemo.dbmanager; import android.content.Context; import android.util.Log; import com.student.dao.StudentDao; import com.student.entity.Student; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; /** * 完成對某一張表的具體操作 ORM 操作的是物件 Student */ public class CommonUtils { private DaoManager manager; private static final String TAG = "CommonUtils"; public CommonUtils(Context context) { this.manager = DaoManager.getInstance(); manager.init(context); } /** * 完成對資料中student 表的插入操作 * * @param student * @return */ public boolean insertStudent(Student student) { boolean flag = false; flag = manager.getDaoSession().insert(student) != -1; Log.e(TAG, "insertStudent: " + flag); return flag; } /** * 同時插入多條記錄,需要開闢新的執行緒 * * @param students * @return */ public boolean insertMultStudent(final List<Student> students) { boolean flag = false; try { manager.getDaoSession().runInTx(new Runnable() { @Override public void run() { for (Student student : students) { manager.getDaoSession().insertOrReplace(student); } } }); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } /** * 完成對student的某一條記錄的修改 * * @param student * @return */ public boolean updateStudent(Student student) { boolean falg = false; try { manager.getDaoSession().update(student); falg = true; } catch (Exception e) { e.printStackTrace(); } return falg; } public boolean deleteStudent(Student student) { boolean falg = false; try { manager.getDaoSession().delete(student);//按照指定的id 進行刪除 delete from student where _id=? falg = true; } catch (Exception e) { e.printStackTrace(); } return false; } public boolean deleteAll() { boolean falg = false; try { manager.getDaoSession().deleteAll(Student.class);//刪除素有的記錄 falg = true; } catch (Exception e) { e.printStackTrace(); } return falg; } /** * 返回多條記錄 * * @return */ public List<Student> queryAll() { return manager.getDaoSession().loadAll(Student.class); } /** * 按照主鍵返回單條記錄 * * @param key * @return */ public Student queryOne(Long key) { return manager.getDaoSession().load(Student.class, key); } public void query1() { //使用native sql進行查詢操作 List<Student> list = manager.getDaoSession().queryRaw(Student.class, "where name like ? and _id > ?", new String[]{"%六%", "3"}); Log.e(TAG, "query1: " + list); } /** * select * from student where name like ? or name =? * < <= != in between and * select * from student where age > 23 and adress like "江西" */ public void query2() { //使用查詢構建器 QueryBuilder<Student> builder = manager.getDaoSession().queryBuilder(Student.class); // 邏輯與 List<Student> list = builder.where(StudentDao.Properties.Age.ge(1)).where(StudentDao.Properties.Address.like("北京")).list(); Log.e(TAG, "query2: "+list.toString() ); } public void query3(){ //select * from student where (address ='北京' or age >21) and name like '%張%' //邏輯與 和邏輯或 是雙目運算子 QueryBuilder<Student> builder = manager.getDaoSession().queryBuilder(Student.class); builder.whereOr(StudentDao.Properties.Address.eq("北京"),StudentDao.Properties.Age.gt(21)); builder.where(StudentDao.Properties.Name.like("張")); builder.whereOr(StudentDao.Properties.Id.ge(new Integer(2)),StudentDao.Properties.Age.ge(21)); //取前三條資料 builder.limit(3); List<Student> list = builder.list(); Log.e(TAG, "query3: "+list ); } }
MainActivity
package com.boradcasst.liuan.greendaodemo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.boradcasst.liuan.greendaodemo.dbmanager.CommonUtils;
import com.student.entity.Student;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
/**
* 新增資料
*/
private Button mBtClick;
private CommonUtils commonUtils;
/**
* 新增資料
*/
private Button mBtInsert;
/**
* 新增多條資料
*/
private Button mBtInsertMult;
/**
* 修改一條資料
*/
private Button mBtUpdata;
/**
* 刪除一條資料
*/
private Button mBtDelete;
/**
* 刪除所有資料
*/
private Button mBtDeleteAll;
/**
* 查詢單條記錄
*/
private Button mBtQuery;
/**
* 查詢所有記錄
*/
private Button mBtQueryAll;
/**
* 使用queryBuilder
*/
private Button mBtQueryBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initData() {
commonUtils = new CommonUtils(this);
}
private void initView() {
mBtClick = (Button) findViewById(R.id.bt_insert);
mBtClick.setOnClickListener(this);
mBtInsert = (Button) findViewById(R.id.bt_insert);
mBtInsert.setOnClickListener(this);
mBtInsertMult = (Button) findViewById(R.id.bt_insert_mult);
mBtInsertMult.setOnClickListener(this);
mBtUpdata = (Button) findViewById(R.id.bt_updata);
mBtUpdata.setOnClickListener(this);
mBtDelete = (Button) findViewById(R.id.bt_delete);
mBtDelete.setOnClickListener(this);
mBtDeleteAll = (Button) findViewById(R.id.bt_delete_all);
mBtDeleteAll.setOnClickListener(this);
mBtQuery = (Button) findViewById(R.id.bt_query);
mBtQuery.setOnClickListener(this);
mBtQueryAll = (Button) findViewById(R.id.bt_query_all);
mBtQueryAll.setOnClickListener(this);
mBtQueryBuilder = (Button) findViewById(R.id.bt_query_builder);
mBtQueryBuilder.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
//插入資料庫
case R.id.bt_insert:
insertData();
break;
case R.id.bt_insert_mult:
insertMultData();
break;
case R.id.bt_updata:
updata();
break;
case R.id.bt_delete:
delete();
break;
case R.id.bt_delete_all:
deleteAll();
break;
case R.id.bt_query:
query();
break;
case R.id.bt_query_all:
queryAll();
break;
case R.id.bt_query_builder:
queryBuilder();
break;
}
}
private void queryBuilder() {
// commonUtils.query1();
commonUtils.query3();
// commonUtils.query2();
}
private void queryAll() {
List<Student> students = commonUtils.queryAll();
Log.e(TAG, "queryAll: " + students.toString());
}
private void query() {
Student student = commonUtils.queryOne(1L);
Log.e(TAG, "query: " + student.toString());
}
private void deleteAll() {
commonUtils.deleteAll();
}
private void delete() {
Student student = new Student();
student.setId(1231153L);
commonUtils.deleteStudent(student);
}
private void updata() {
//update student set name='jack' where id=1001;
Student student = new Student();
student.setId(1231153L);
student.setAge(100);
student.setName("Jack");
student.setAddress("惠科");
commonUtils.updateStudent(student);
}
private void insertMultData() {
Log.e(TAG, "insertMultData: ");
List<Student> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setAddress("山東");
student.setAge(18);
student.setName("小六" + i);
list.add(student);
}
commonUtils.insertMultStudent(list);
}
private void insertData() {
Log.e(TAG, "insertData: ");
Student student1 = getStudent("北京",15,"張三");
Student student2 = getStudent("山東",20,"李四");
Student student3 = getStudent("江西",20,"王五");
Student student4 = getStudent("深圳",25,"小六");
// student.setId(1231153L);
commonUtils.insertStudent(student1);
commonUtils.insertStudent(student2);
commonUtils.insertStudent(student3);
commonUtils.insertStudent(student4);
}
@NonNull
private Student getStudent(String adress,int age,String name) {
Student student = new Student();
student.setAddress(adress);
student.setAge(age);
student.setName(name);
return student;
}
}
<?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">
<Button
android:id="@+id/bt_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="新增資料" />
<Button
android:id="@+id/bt_insert_mult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="新增多條資料" />
<Button
android:id="@+id/bt_updata"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="修改一條資料" />
<Button
android:id="@+id/bt_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="刪除一條資料" />
<Button
android:id="@+id/bt_delete_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="刪除所有資料" />
<Button
android:id="@+id/bt_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查詢單條記錄" />
<Button
android:id="@+id/bt_query_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查詢所有記錄" />
<Button
android:id="@+id/bt_query_builder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="使用queryBuilder" />
</LinearLayout>