市場上大多數的android數據庫加密都是基於sqlcipher來做的,集成方便,版本穩定,今天要來介紹的miniorm-sqlcipher也是這樣。
廢話不多說,切入正題,該加密數據庫是基於miniorm-for-android來改造,並且加入sqlcipher的,Miniorm的原理請點擊這裏。下面來說一下 加密數據庫的優點。
1.開發人員只需在gradle方式引入。
2.侵入小,以litepal爲例,需要繼承它的子類,而 Miniorm-sqlcipher完全不需要繼承任何類,只需要在類裏面加入註解就行。
框架採用編譯時註解和運行時註解來作爲底層的實現方式,開發人員完全不用關心底層 是如何運作。
下面就說一下引入方式。
//gradle 5.0以上引入方式
kapt 'com.github.mengleigithub:miniorm-compiler:1.0.7'
//gradle 5.0以下引入方式
annotationProcessor 'com.github.mengleigithub:miniorm-compiler:1.0.7'
//基礎數據庫必須引入(如果不需要加密,只需要引入這一個就行)
implementation 'com.github.mengleigithub:miniorm-core:2.0.8-beta-2'
//加密數據庫
implementation 'com.github.mengleigithub:miniorm-sqlcipher:1.1.1-bate-1.0'
implementation 'net.zetetic:android-database-sqlcipher:4.2.0@aar'
引入成功之後,
初始化框架:
MiniOrmUtils.getInstance().init(getApplication(),"test.db",1,"password");
MiniOrmUtils.getInstance().createTables();
- test.db是數據庫的表明
- 1表示數據庫版本
- password是數據庫的密碼,可隨意設置,但不能爲空
- MiniOrmUtils.getInstance().createTables();是建表操作
注意事項:如果數據庫設置爲外部數據庫也就是存在於sdcard上面,需要先獲取到權限,才能調用createTables方法,否則崩潰
開始設置表名。
設置如下(非加密):
@Table(name = "course")
public class Course {
//表的主鍵
@TableID(name = "cid",type = Parmary.CUSTOM,columnType = ColumnType.INTEGER)
private long id;
@TableColumn(name = "cname",columnType = ColumnType.VARCHAR)
private String cName;
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
數據庫加密的部分,只需要在 Course上面加上@Sqlcipher就可以了,例:
@Sqlcipher
@Table(name = "course")
public class Course {
//表的主鍵
@TableID(name = "cid",type = Parmary.CUSTOM,columnType = ColumnType.INTEGER)
private long id;
@TableColumn(name = "cname",columnType = ColumnType.VARCHAR)
private String cName;
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
存數據:
//批量
List<Course> courses = new ArrayList<>();
for (int i = 1; i <= cours.length; i++) {
Course course = new Course();
course.setcName(cours[i - 1]);
course.setId(i);
courses.add(course);
}
MiniOrmUtils.getInstance().getDao(Course.class).saveOrUpdate(courses);
//單個
Course course = new Course();
course.setcName("測試");
course.setId(1);
MiniOrmUtils.getInstance().getDao(Course.class).saveOrUpdate(course);
所有的增刪改查和Miniorm-for-android的操作一樣,在此不做一一贅述。
詳細demo和源碼 請看這裏 https://github.com/MengLeiGitHub/miniOrm-for-android