一、概述
Android數(shù)據(jù)庫(kù)在存儲(chǔ)數(shù)據(jù)方面很重要痕鳍,我們項(xiàng)目當(dāng)中一般用的SQLiteOpenHelper這個(gè)類(lèi)進(jìn)行數(shù)據(jù)庫(kù)的創(chuàng)建阱穗,升級(jí)罢屈,然后在用數(shù)據(jù)庫(kù)操作類(lèi)(譬如UserDao)進(jìn)行增刪改查俘种,整個(gè)設(shè)計(jì)都是面向過(guò)程的秤标,可擴(kuò)展性不高,現(xiàn)在我們以面向?qū)ο蟮慕嵌葋?lái)設(shè)計(jì)數(shù)據(jù)庫(kù)宙刘。
整個(gè)設(shè)計(jì)所設(shè)計(jì)到的知識(shí)點(diǎn):
泛型 注解 反射
數(shù)據(jù)庫(kù)語(yǔ)句拼接
設(shè)計(jì)模式
1苍姜、單例模式 2、簡(jiǎn)單工廠模式 3悬包、模板方法模式
對(duì)于簡(jiǎn)單工廠模式和模板方法模式不太懂的可以看我的這兩篇博客
簡(jiǎn)單工廠模式
模板方法模式
二衙猪、整個(gè)的一個(gè)設(shè)計(jì)思路
我用一張圖表示:
對(duì)于這張圖,我解釋幾點(diǎn)
1、整張圖就是調(diào)用端activity通過(guò)調(diào)用BaseDaoFactory實(shí)例化數(shù)據(jù)庫(kù)操作類(lèi)(userDao)插入一條數(shù)據(jù)屈嗤。
2、調(diào)用層不關(guān)系數(shù)據(jù)庫(kù)的創(chuàng)建在哪里創(chuàng)建吊输,不關(guān)心表的創(chuàng)建饶号,不關(guān)心sql語(yǔ)句的拼寫(xiě)。
3季蚂、BaseDaoFactory是創(chuàng)建BaseDao的工廠類(lèi)茫船,用到了工廠設(shè)計(jì)模式,其本身又是一個(gè)單例模式扭屁,BaseDao里面提供了創(chuàng)建表的語(yǔ)句算谈,由具體操作數(shù)據(jù)庫(kù)的子類(lèi)去實(shí)現(xiàn),這正體現(xiàn)了模板方法模式料滥。
4然眼、對(duì)象的成員變量和表的列名是一一對(duì)應(yīng)關(guān)系,不是說(shuō)表的字段名就一定是成員變量名稱葵腹,用戶可以通過(guò)注解設(shè)置在要操作的類(lèi)的成員變量上高每,以此來(lái)產(chǎn)生映射關(guān)系。
三践宴、具體代碼細(xì)節(jié)
IBaseDao接口鲸匿,提供數(shù)據(jù)庫(kù)操作的方法(增刪改查)
public interface IBaseDao<T> {
//插入數(shù)據(jù)
Long insert(T t);
Long update(T entity,T where);
}
插入的數(shù)據(jù)不知道,用泛型表示
我們看他的實(shí)現(xiàn)類(lèi)阻肩,BaseDao
public abstract class BaseDao<T> implements IBaseDao<T> {
private SQLiteDatabase mDatabase;
private boolean isInit = false; //保證實(shí)例化一次
//持有操作數(shù)據(jù)庫(kù)表對(duì)應(yīng)的Java類(lèi)型
private Class<T> entityClass;
//維護(hù)這表名與成員變量名的映射關(guān)系
private HashMap<String, Field> cacheMap;
//表名
private String tableName;
protected synchronized boolean init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
if (!isInit) {
this.entityClass = entity; //給操作數(shù)據(jù)庫(kù)表對(duì)應(yīng)的類(lèi)型賦值
mDatabase = sqLiteDatabase;
if (entityClass.getAnnotation(DbTable.class).value() == null) { 1
tableName = entityClass.getSimpleName();
} else {
tableName = entityClass.getAnnotation(DbTable.class).value();
}
if (!mDatabase.isOpen()) {
return false;
}
if (!TextUtils.isEmpty(createTable())) { 2 //創(chuàng)建表的語(yǔ)句
sqLiteDatabase.execSQL(createTable()); //創(chuàng)建表
}
//實(shí)體類(lèi)的成員變量和表的字段名的映射關(guān)系的緩存集合
cacheMap = new HashMap<>();
initCacheMap(); 3
isInit = true;
}
return isInit;
}
//維護(hù)映射關(guān)系
private void initCacheMap() {
String sql = "select * from " + this.tableName + " limit 1 , 0";
Cursor cursor = null;
try {
cursor = mDatabase.rawQuery(sql, null);
String[] columns = cursor.getColumnNames(); //表的列名數(shù)組
//拿到fields數(shù)組
Field[] columsFileds = entityClass.getFields();
for (Field field : columsFileds) {
field.setAccessible(true); //暴力反射
}
//開(kāi)始找對(duì)應(yīng)關(guān)系
for (String columsName : columns) {
Field columFiled = null;
for (Field filed : columsFileds) {
String fieldName = null;
if (!TextUtils.isEmpty(filed.getAnnotation(DbFiled.class).value())) {
//如果字段上面有對(duì)應(yīng)的數(shù)據(jù)庫(kù)列名
fieldName = filed.getAnnotation(DbFiled.class).value();
} else {
fieldName = filed.getName();
}
//如果表的列名等于了成員變量的注解的名字或者成員變量的名字
if (fieldName.equals(columsName)) {
columFiled = filed; //賦值
break;
}
}
//找到了對(duì)應(yīng)關(guān)系
if (columFiled != null) {
cacheMap.put(columsName, columFiled);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
}
}
//將T entity轉(zhuǎn)換為map
public Map<String, String> getValues(T entity) {
HashMap<String, String> result = new HashMap<>();
Iterator<Field> fieldIterator = cacheMap.values().iterator();
// 循環(huán)遍歷 映射map的 Filed
while (fieldIterator.hasNext()) {
Field colmunToFiled = fieldIterator.next();
String cacheKey = null;
String cacheValue = null;
if (colmunToFiled.getAnnotation(DbFiled.class).value() != null) {
cacheKey = colmunToFiled.getAnnotation(DbFiled.class).value();
} else {
cacheKey = colmunToFiled.getName();
}
try {
if (null == colmunToFiled.get(entity)) {
continue;
}
cacheValue = colmunToFiled.get(entity).toString();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
result.put(cacheKey, cacheValue);
}
return result;
}
/**
* 將map 轉(zhuǎn)換為ContentValues
*
* @return
*/
public ContentValues getContentValues(Map<String, String> map) {
ContentValues contentValues = new ContentValues();
Set keys = map.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = map.get(key);
if (value != null) {
contentValues.put(key, value);
}
}
return contentValues;
}
//創(chuàng)建數(shù)據(jù)庫(kù)表的語(yǔ)句
public abstract String createTable(); 6
@Override
public Long insert(T entity) {
5
Map<String,String> map = getValues(entity);
ContentValues contentValues = getContentValues(map);
Long result = mDatabase.insert(tableName,null,contentValues);
return result;
}
@Override
public Long update(T entity, T where) {
return null;
}
}
分析下這個(gè)類(lèi)带欢,主要功能都集中在init方法里面。
在代碼1處烤惊,通過(guò)if判斷當(dāng)期類(lèi)有沒(méi)有加上表名的注解乔煞,給表名tabName賦值。
代碼2處通過(guò)判斷創(chuàng)建表的語(yǔ)句是否為空撕氧,來(lái)創(chuàng)建表瘤缩,createTable方法給具體子類(lèi)實(shí)現(xiàn),代碼在6處伦泥。
在代碼4處剥啤,初始化hashMap維護(hù)實(shí)體bean類(lèi)的成員變量和表的字段名的映射關(guān)系,key為String類(lèi)型不脯,value為Filed類(lèi)型府怯。具體的邏輯請(qǐng)看代碼。
在代碼5處就是將map集合字段名和字段值轉(zhuǎn)換為ContentValues防楷,然后進(jìn)行插入數(shù)據(jù)庫(kù)操作牺丙。
這個(gè)類(lèi)分析大概就這么多,涉及到的其他類(lèi)的代碼我這里貼一下
DbTable注解類(lèi)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DbTable {
String value();
}
這個(gè)類(lèi)就是給實(shí)體類(lèi)指定一個(gè)表名沒(méi)有指定默認(rèn)為類(lèi)名,譬如這里的User類(lèi)
@DbTable("tb_user")
public class User {
public User(String name,String password){
this.password = password;
this.name = name;
}
public User(){
}
@DbFiled("password")
public String password;
@DbFiled("name")
public String name;
}
DbTable指定表名通過(guò)這個(gè)注解和數(shù)據(jù)庫(kù)表名產(chǎn)生映射關(guān)系冲簿,這個(gè)User類(lèi)的成員變量用到了DbFiled注解粟判,用于指定字段名。貼代碼:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DbFiled {
String value();
}
這是數(shù)據(jù)庫(kù)操作基類(lèi)峦剔,我們接著看具體的操作類(lèi)UserDao
public class UserDao<User> extends BaseDao<User>{
@Override
public String createTable() {
return "create table if not exists tb_user(name varchar(20),password varchar(10))";
}
}
這個(gè)類(lèi)主要是就是返回了創(chuàng)建數(shù)據(jù)庫(kù)表的語(yǔ)句档礁,邏輯都是父類(lèi)給處理了,指定了泛型吝沫。
好呻澜,我們最后看下數(shù)據(jù)庫(kù)操作工廠類(lèi)
/**
* Created by dell on 2017/7/16.
* 數(shù)據(jù)庫(kù)操作工程類(lèi)
*/
public class BaseDaoFactory {
private String mSqlitePath;
private SQLiteDatabase mSqliteDatabase;
private static BaseDaoFactory instance = new BaseDaoFactory(); 1
public BaseDaoFactory() {
mSqlitePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/student.db";2
openDataBase();3
}
public synchronized <T extends BaseDao<M>,M> T getDataHelper(Class<T> clazz,Class<M> entityClass){
BaseDao baseDao = null;
try {
baseDao = clazz.newInstance();
baseDao.init(entityClass,mSqliteDatabase);
} catch (Exception e) {
e.printStackTrace();
}
return (T) baseDao;
}
private void openDataBase() {
this.mSqliteDatabase = SQLiteDatabase.openOrCreateDatabase(mSqlitePath, null);
}
public static BaseDaoFactory getInstance(){
return instance;
}
}
單例模式,路徑放在sd卡的根目錄惨险,創(chuàng)建數(shù)據(jù)庫(kù)羹幸,這是1,2,3處代碼做的操作。
getDataHelper方法的泛型T表示BaseDao的子類(lèi)辫愉,也就是具體的操作數(shù)據(jù)庫(kù)類(lèi)栅受,繼承自BaseDao由用戶去實(shí)現(xiàn),擴(kuò)展性高一屋,M表示插入的實(shí)體類(lèi)型窘疮,通過(guò)反射實(shí)例化BaseDao然后調(diào)用init方法進(jìn)行初始化。最后返回BaseDao的子類(lèi)冀墨。也就是生產(chǎn)數(shù)據(jù)庫(kù)操作類(lèi)闸衫。
最后一步,調(diào)用端:
在MainActivity中我們這樣操作:
public class MainActivity extends Activity {
UserDao userDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userDao = BaseDaoFactory.getInstance().getDataHelper(UserDao.class, User.class);
}
public void save(View view) {
for (int i=0;i<4;i++){
User user = new User("lcty", "123456");
userDao.insert(user);
}
}
}
操作圖和效果圖搞起:
點(diǎn)擊save保存四條數(shù)據(jù)
看插入的數(shù)據(jù):
好诽嘉,我們看到數(shù)據(jù)已經(jīng)插入成功蔚出,分析完畢,有說(shuō)的不對(duì)的地方望指正虫腋,多多交流骄酗。