1. 程式人生 > >greendao3.0以上使用步驟(三):資料庫加密

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

相關推薦

greendao3.0以上使用步驟資料庫加密

引入資料庫 1、在專案的build.gradle中加入這些配置 // Top-level build file where you can add configuration options common to all sub-projects/

greendao3.0以上使用步驟資料庫到底該怎麼升級

這一篇看看資料庫到底該怎麼升級呢?看我升級後的效果 沒有升級前的頁面顯示 沒有升級前的資料庫 升級後的頁面顯示 升級後的資料庫 看增加了一個NUM欄位 。 最新有小夥伴遇到資料庫升級問題了,說網上都是2.0版本的升級方法,

我對hyperledger fabric1.1.0的執著執行e2e_cli測試案例以及踩過的坑

1、執行e2e_cli案例: (1.1)下載平臺特定二進位制檔案,如圖下載對應版本,下載地址為: https://nexus.hyperledger.org/content/repositories/releases/org/hyperledger/fabric/hyperledger-fa

推送系統從0到1推送任務的建立

如何保證把內容準確無誤地投遞給想要投遞的人,這將會是推送系統通訊層面的難點。 上一篇文章已經講述瞭如何選擇推送服務,並梳理了使用者與裝置、Token之間的關係,用裝置號才能精準的標識使用者。如果還無法清晰的瞭解這三者的關係,可以回顧上一篇文章:推送系統從0到1(二)

VUE2.0學習筆記如何設定當前頁面的背景色

程式碼如下:<template>    <div>    //div裡面的程式碼省略了.div代表下圖中灰色的容器    <div></template><style scoped>div{    width: 10

程式設計師之網路安全系列資料加密之對稱加密演算法

系列目錄: 前文回顧 假如,明明和麗麗相互不認識,明明想給麗麗寫一封情書,讓隔壁老王送去 如何保證隔壁老王不能看到情書內容?(保密性) 如何保證隔壁老王不修改情書的內容?(完整性) 如何保證隔壁老王不冒充明明?(身份認證) 如何保證明明不能否認情書是自己寫的?(來源的不可否認) 上一節,我們使用了Ha

Spring Security入門密碼加密

前文導讀Github 地址https://github.com/ChinaSilence/any

greendao3.0以上使用步驟基礎使用

本文介紹了greendao的基礎入門使用:其中包括資料庫的增刪改查,基本使用功能,簡單方便,易懂。 優勢: 1:效能最大化 2:記憶體開銷最小 3:API 簡單好用 4:對Android 高度優化 5:2.2版本以上還支援加密資料庫 6:

Elam的caffe筆記之配置篇Centos 6.5下裝CUDA8.0 和cudnnv5.1

Elam的caffe筆記之配置篇(三):Centos 6.5下裝CUDA8.0 和cudnnv5.1 配置要求: 系統:centos6.5 目標:基於CUDA8.0+Opencv3.1+Cudnnv5.1+python3.6介面的caffe框架 寫在前面,本文是在C

微服務架構實戰篇Spring boot2.0 + Mybatis + PageHelper實現增刪改查和分頁查詢功能

簡介 該專案主要利用Spring boot2.0 +Mybatis + PageHelper實現增刪改查和分頁查詢功能,快速搭建一套和資料庫互動的專案。 小工具一枚,歡迎使用和Star支援,如使用過程中碰到問題,可以提出Issue,我會盡力完善該Starter 版本基礎

微服務 SpringBoot 2.0啟動剖析之@SpringBootApplication

我原以為就一個註解,背後竟然還有3個 —— Java面試必修 引言 前面兩章我們先後認識了SpringBoot和它的極簡配置,為新手入門的學習降低了門檻,會基本的使用後,接下來我們將進一步認識SpringBoot,它為何能做到服務秒開,就來跟隨我一起分析SpringBoot執行啟動的原理吧。 啟動原理分2

BitShares2.0 —— 第一章 創世篇創世紀 執行見證節

NODE (節點) 節點種類 英文抄自官方文件 Full node 全節點 (non-block producing witness nodes 不產塊的見證人節點) block producing

java入門練習題讀入一組整數不超過20個,當用戶輸入0時,表示輸入結束;然後程式將從這組整數中,把第二大的整數找出來,並把它打印出來。

 程式意義:讀入一組整數(不超過20個),當用戶輸入0時,表示輸入結束;然後程式將從這組整數中,把第二大的整數找出來,並把它打印出來。  說明:(1)0表示輸入結束,它本身並不計入這組整數中。            (2)在這組整數中,既有整數又有負數;          

【鏈塊技術55期】超級賬本Fabric教程Hyperledger Fabric 1.0架構及原理

原文連結:超級賬本Fabric教程(三):Hyperledger Fabric 1.0架構及原理   如果說以比特幣為代表的貨幣區塊鏈技術為 1.0,以以太坊為代表的合同區塊鏈技術為 2.0,那麼實現了完備的許可權控制和安全保障的 Hyperledger 專案毫無疑問代表著區塊鏈技

NPOI 2.0 教程EXCEL 基本格式設定之ICellStyle

轉載請註明出處 http://blog.csdn.net/fujie724 前兩篇,我們已經學習瞭如何用NPOI來建立和編輯Excel,並且已經熟悉了HSSFWorkbook,ISheet,IRow和ICell。 接下來我們把它變得漂亮一點。 ICellStyle——單

vue-cli 3.0腳手架配置及擴充套件 config.app.js應用目錄配置

工程目錄如圖,config.app.js檔案在src原始碼目錄下config.app.js檔案是我為了方便測試模擬的專案結構,程式碼如下:/** * @fileOverview app配置 * @author Franks.T.D * @date 2018/06/17

Java基礎總結從0開始Java反射原理

反射:Java虛擬機器允許執行時獲取類的資訊。  2.1 反射的常用方法:        a.forName(String className) :           返回與帶有給定字串名的類或介面相關聯的 Class 物件。        b.forName(String

Docker學習筆記Dockerfile及多步驟構建映象

## Dockerfile指令 官方文件地址:https://docs.docker.com/engine/reference/builder/ Dockerfile是一個文字格式的配置檔案,其內容包含眾多指令,使用者可以使用它快速的建立自定義映象。 ### 部分指令列表 指令|作用|備註 -|-|- FRO

Java多線程編程模式實戰指南Two-phase Termination模式

增加 row throws mgr 額外 finally join table 還需 停止線程是一個目標簡單而實現卻不那麽簡單的任務。首先,Java沒有提供直接的API用於停止線程。此外,停止線程時還有一些額外的細節需要考慮,如待停止的線程處於阻塞(等待鎖)或者等待狀態(等

SpringSpring整合Hibernate

ng- checkout wait 哪些 check driver eas package class 背景:   本文主要介紹使用spring-framework-4.3.8.RELEASE與hibernate-release-5.2.9.Final項目整合搭建