android 面向?qū)ο髷?shù)據(jù)庫編程

面向?qū)ο髷?shù)據(jù)庫編程

我們先看看操作示例

我們可以看到這里操作數(shù)據(jù)庫只是引用了一個(gè)對(duì)象

        IBaseDao<Person> baseDao = BaseDaoFactory.getInstance().getBaseDao(Person.class);
        Person person = new Person();
        person.name = "熊大";
        person.setPassword(123456l);
        baseDao.insert(person);

從上面的操作示例我們可以看到
1.自動(dòng)建表
2.面向?qū)ο蟛迦?/p>

我們先看一下BaseDaoFactory.getInstance().getBaseDao(Person.class);
從這里面的代碼我們可以看到 這里調(diào)用SQLiteDatabase.openOrCreateDatabase(sqlPath, null);創(chuàng)建了一個(gè)庫
getBaseDao(Class<T> entityClass)里面創(chuàng)建了一個(gè)BaseDao實(shí)例調(diào)用了init方法進(jìn)行了初始化

public class BaseDaoFactory {
    private static BaseDaoFactory ourInstance;
    private final SQLiteDatabase mSqLiteDatabase;

    public static BaseDaoFactory getInstance() {
        if (ourInstance == null) {
            ourInstance = new BaseDaoFactory();
        }
        return ourInstance;
    }

    private BaseDaoFactory() {
        String sqlPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/app.db";
        mSqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqlPath, null);

    }

    public synchronized <T>BaseDao getBaseDao(Class<T> entityClass) {
        BaseDao<T> baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(entityClass,mSqLiteDatabase);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  baseDao;

    }
}

緊接著我們看一下 baseDao.init(entityClass,mSqLiteDatabase);
這段代碼我們可以看到 tableName = entityClass.getAnnotation(DBTable.class).value();
createTbale() 創(chuàng)建表的動(dòng)作
這里獲取了表明

    public synchronized void init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
        if (!isInit) {
            entityClass = entity;
            mSQLiteDatabase = sqLiteDatabase;
            tableName = entityClass.getAnnotation(DBTable.class).value();
            createTbale();
            initCacheMap();
            isInit = true;
        }
    }

上述代碼我們看到 表名通過 獲取實(shí)體類里的注解拿到的
那么我們看一下Person

我們可以看到@DBTable @DBFiled
@DBTable 表名 @DBFiled字段名

@DBTable("tb_person")
public class Person {


    @DBFiled("tb_name")
    public String name;
    @DBFiled("tb_password")
    public Long password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getPassword() {
        return password;
    }

    public void setPassword(Long password) {
        this.password = password;
    }
}

@Target(ElementType.FIELD)//作用在成員變量上
@Retention(RetentionPolicy.RUNTIME)//運(yùn)行時(shí)
public @interface DBFiled {
    String value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
    String value();
}

上述代碼我們看到了createTbale();創(chuàng)建表的一個(gè)操作我們看下是如何自動(dòng)創(chuàng)建表的,我們看到是一個(gè)sql語句的拼接

    private void createTbale() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("create table if not exists ");
        stringBuilder.append(tableName);
        stringBuilder.append("(");
       //獲得某個(gè)類的所有聲明的字段,即包括public、private和proteced疟位,但是不包括父類的申明字段。
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            Class type = field.getType();
            if (type == String.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " TEXT,");
            } else if (type == Double.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " DOUBLE,");
            } else if (type == Integer.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " INTEGER,");
            } else if (type == Float.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " FLOAT,");
            } else if (type == byte[].class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BLOB,");
            } else if (type == Long.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BIGINT,");
            } else {
                continue;
            }
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        stringBuilder.append(")");
      
        this.mSQLiteDatabase.execSQL(stringBuilder.toString());

    }

剩下最后一步 通過對(duì)象插入數(shù)據(jù) baseDao.insert(person); 遍歷拿到字段名key, field.get(entity);拿到對(duì)應(yīng)的屬性

    @Override
    public void insert(T entity) {
        ContentValues contentValues = getValuse(entity);
        mSQLiteDatabase.insert(tableName, null, contentValues);
    }

    private ContentValues getValuse(T entity) {
        ContentValues contentValues = new ContentValues();
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();

            field.setAccessible(true);
            try {
                Object object = field.get(entity);
                Class type = field.getType();
                if (type == String.class) {
                    String vlaue = (String) object;
                    contentValues.put(key, vlaue);
                } else if (type == Double.class) {
                    Double vlaue = (Double) object;
                    contentValues.put(key, vlaue);
                } else if (type == Integer.class) {
                    Integer vlaue = (Integer) object;
                    contentValues.put(key, vlaue);
                } else if (type == Float.class) {
                    Float vlaue = (Float) object;
                    contentValues.put(key, vlaue);
                } else if (type == byte[].class) {
                    byte[] vlaue = (byte[]) object;
                    contentValues.put(key, vlaue);
                } else if (type == Long.class) {
                    Long vlaue = (Long) object;
                    contentValues.put(key, vlaue);
                } else {
                    continue;
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return contentValues;
    }

代碼

Annotation
@Target(ElementType.FIELD)//作用在成員變量上
@Retention(RetentionPolicy.RUNTIME)//運(yùn)行時(shí)
public @interface DBFiled {
    String value();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
    String value();
}



BaseDaoFactory

public class BaseDaoFactory {
    private static BaseDaoFactory ourInstance;
    private final SQLiteDatabase mSqLiteDatabase;

    public static BaseDaoFactory getInstance() {
        if (ourInstance == null) {
            ourInstance = new BaseDaoFactory();
        }
        return ourInstance;
    }

    private BaseDaoFactory() {
        String sqlPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/app.db";
        mSqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqlPath, null);

    }

    public synchronized <T>BaseDao getBaseDao(Class<T> entityClass) {
        BaseDao<T> baseDao = null;
        try {
            baseDao = BaseDao.class.newInstance();
            baseDao.init(entityClass,mSqLiteDatabase);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  baseDao;

    }
}

BaseDao

public interface IBaseDao<T> {

   void insert(T entity);
   List<T> query(T where);
   void delte(T entity);
   void update(T oldEntity ,T newEntity);
}

public class BaseDao<T> implements IBaseDao<T> {
    /**
     * 持有數(shù)據(jù)操作引用
     */
    private SQLiteDatabase mSQLiteDatabase;
    /**
     * 操作的實(shí)體類
     */
    private Class<T> entityClass;

    /**
     * 表名
     */
    private String tableName;

    /**
     *緩存表的映射關(guān)系
     */
    private HashMap<String, Field> cacheMap;

    /**
     * 是否初始化
     */
    private boolean isInit = false;



    public synchronized void init(Class<T> entity, SQLiteDatabase sqLiteDatabase) {
        if (!isInit) {
            entityClass = entity;
            mSQLiteDatabase = sqLiteDatabase;
            tableName = entityClass.getAnnotation(DBTable.class).value();
            createTbale();
            initCacheMap();
            isInit = true;
        }
    }


    /**
     * 表的映射關(guān)系
     */
    private void initCacheMap() {
        cacheMap = new HashMap<>();
        String sql = "select  * from " + tableName + " limit 1,0";
        Cursor cursor = mSQLiteDatabase.rawQuery(sql, null);
        //獲取表里面的字段名
        String[] columnNames = cursor.getColumnNames();
       // 獲得該類的所有的公共(public)的字段店乐,包括父類中的字段。
        Field[] columnFields = entityClass.getFields();

        for (String columnName : columnNames) {
            Field reslutField = null;
            for (Field field : columnFields) {
                if (columnName.equals(field.getAnnotation(DBFiled.class).value())) {
                    reslutField = field;
                    break;
                }
            }
            if (reslutField != null) {
                cacheMap.put(columnName, reslutField);
            }
        }
        cursor.close();

    }

    private static final String TAG = "BaseDao";

    private void createTbale() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("create table if not exists ");
        stringBuilder.append(tableName);
        stringBuilder.append("(");
       //獲得某個(gè)類的所有聲明的字段呻袭,即包括public眨八、private和proteced,但是不包括父類的申明字段左电。
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            Class type = field.getType();
            if (type == String.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " TEXT,");
            } else if (type == Double.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " DOUBLE,");
            } else if (type == Integer.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " INTEGER,");
            } else if (type == Float.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " FLOAT,");
            } else if (type == byte[].class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BLOB,");
            } else if (type == Long.class) {
                stringBuilder.append(field.getAnnotation(DBFiled.class).value() + " BIGINT,");
            } else {
                continue;
            }
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        stringBuilder.append(")");

        this.mSQLiteDatabase.execSQL(stringBuilder.toString());

    }


    private ContentValues getValuse(T entity) {
        ContentValues contentValues = new ContentValues();
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();

            field.setAccessible(true);
            try {
                Object object = field.get(entity);
                Class type = field.getType();
                if (type == String.class) {
                    String vlaue = (String) object;
                    contentValues.put(key, vlaue);
                } else if (type == Double.class) {
                    Double vlaue = (Double) object;
                    contentValues.put(key, vlaue);
                } else if (type == Integer.class) {
                    Integer vlaue = (Integer) object;
                    contentValues.put(key, vlaue);
                } else if (type == Float.class) {
                    Float vlaue = (Float) object;
                    contentValues.put(key, vlaue);
                } else if (type == byte[].class) {
                    byte[] vlaue = (byte[]) object;
                    contentValues.put(key, vlaue);
                } else if (type == Long.class) {
                    Long vlaue = (Long) object;
                    contentValues.put(key, vlaue);
                } else {
                    continue;
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return contentValues;
    }

    @Override
    public void insert(T entity) {
        ContentValues contentValues = getValuse(entity);
        mSQLiteDatabase.insert(tableName, null, contentValues);
    }

    @Override
    public List<T> query(T where) {
        List<T> list = new ArrayList<>();
        String condition = getCondition(where);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select * from ");
        stringBuffer.append(tableName);
        stringBuffer.append(" where ");
        stringBuffer.append(condition);
        Cursor cursor = mSQLiteDatabase.rawQuery(stringBuffer.toString(), null);
        while (cursor.moveToNext()) {
            try {
                T t = (T) where.getClass().newInstance();
                Field[] fields = t.getClass().getFields();
                String[] strings = cursor.getColumnNames();

                for (Field field : fields) {
                    String key = field.getAnnotation(DBFiled.class).value();
                    for (String string : strings) {
                        if (key.equals(string)) {
                            Class<?> type = field.getType();
                            if (type == String.class) {
                                field.set(t, cursor.getString(cursor.getColumnIndex(string)));
                            } else if (type == Double.class) {
                                field.set(t, cursor.getDouble(cursor.getColumnIndex(string)));
                            } else if (type == Integer.class) {
                                field.set(t, cursor.getInt(cursor.getColumnIndex(string)));
                            } else if (type == Float.class) {
                                field.set(t, cursor.getFloat(cursor.getColumnIndex(string)));
                            } else if (type == byte[].class) {
                                field.set(t, cursor.getBlob(cursor.getColumnIndex(string)));
                            } else if (type == Long.class) {
                                field.set(t, cursor.getLong(cursor.getColumnIndex(string)));
                            } else {
                                continue;
                            }
                        }
                    }

                }
                list.add(t);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        cursor.close();
        return list;
    }

    @Override
    public void delte(T entity) {
        String condition = getCondition(entity);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("delete from ");
        stringBuffer.append(tableName);
        stringBuffer.append(" where ");
        stringBuffer.append(condition);
        mSQLiteDatabase.execSQL(stringBuffer.toString());
    }

    /**
     * @param oldEntity 更新條件
     * @param newEntity 更新的字段
     * @return
     */
    @Override
    public void update(T oldEntity, T newEntity) {

        String old = getCondition(oldEntity);
        String n = getCondition(newEntity, " , ");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("update ");
        stringBuffer.append(tableName);
        stringBuffer.append(" set ");
        stringBuffer.append(n);
        stringBuffer.append(" where ");
        stringBuffer.append(old);
        Log.i(TAG, "update: " + stringBuffer.toString());
        mSQLiteDatabase.execSQL(stringBuffer.toString());
    }


    private String getCondition(T entity) {
        return getCondition(entity, " and ");
    }

    private String getCondition(T entity, String tag) {
        Iterator<Map.Entry<String, Field>> iterator = cacheMap.entrySet().iterator();
        StringBuffer stringBuffer = new StringBuffer();
        while (iterator.hasNext()) {
            Map.Entry<String, Field> fieldEntry = iterator.next();
            Field field = fieldEntry.getValue();
            //表的字段名
            String key = fieldEntry.getKey();
            try {
                Object object = field.get(entity);
                if (object != null) {
                    if (stringBuffer.length() > 0) {
                        stringBuffer.append(tag);
                    }
                    stringBuffer.append(key);
                    stringBuffer.append(" = ");
                    stringBuffer.append("'");
                    stringBuffer.append(object.toString());
                    stringBuffer.append("'");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

}

Person 可以任意創(chuàng)建這里只是個(gè)演示bean

@DBTable("tb_person")
public class Person {


    @DBFiled("tb_name")
    public String name;
    @DBFiled("tb_password")
    public Long password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getPassword() {
        return password;
    }

    public void setPassword(Long password) {
        this.password = password;
    }
}

實(shí)際操作

        final IBaseDao<Person> baseDao = BaseDaoFactory.getInstance().getBaseDao(Person.class);
        findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                person.setPassword(password++);
                baseDao.insert(person);
            }
        });

        findViewById(R.id.remove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                person.password = password++;
                baseDao.delte(person);
            }
        });
        findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person person = new Person();
                person.name = name;
                List<Person> list = baseDao.query(person);
                for (Person person1 : list) {
                    Log.i(TAG, "name= " + person1.name + " passowrd=" + person1.password);
                }
            }
        });

        findViewById(R.id.update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Person old = new Person();
                old.name = name;
                old.password = 26l;
                Person n = new Person();
                n.name = "無敵";
                baseDao.update(old, n);
            }
        });

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末踪古,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子券腔,更是在濱河造成了極大的恐慌伏穆,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纷纫,死亡現(xiàn)場離奇詭異枕扫,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)辱魁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門烟瞧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來诗鸭,“玉大人,你說我怎么就攤上這事参滴∏堪叮” “怎么了?”我有些...
    開封第一講書人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵砾赔,是天一觀的道長蝌箍。 經(jīng)常有香客問我,道長暴心,這世上最難降的妖魔是什么妓盲? 我笑而不...
    開封第一講書人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮专普,結(jié)果婚禮上悯衬,老公的妹妹穿的比我還像新娘。我一直安慰自己檀夹,他們只是感情好筋粗,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著炸渡,像睡著了一般娜亿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上偶摔,一...
    開封第一講書人閱讀 49,007評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音促脉,去河邊找鬼辰斋。 笑死,一個(gè)胖子當(dāng)著我的面吹牛瘸味,可吹牛的內(nèi)容都是我干的宫仗。 我是一名探鬼主播,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼旁仿,長吁一口氣:“原來是場噩夢啊……” “哼藕夫!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起枯冈,我...
    開封第一講書人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤毅贮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后尘奏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體滩褥,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年炫加,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瑰煎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铺然。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖酒甸,靈堂內(nèi)的尸體忽然破棺而出魄健,到底是詐尸還是另有隱情,我是刑警寧澤插勤,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布沽瘦,位于F島的核電站,受9級(jí)特大地震影響饮六,放射性物質(zhì)發(fā)生泄漏其垄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一卤橄、第九天 我趴在偏房一處隱蔽的房頂上張望绿满。 院中可真熱鬧,春花似錦窟扑、人聲如沸喇颁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽橘霎。三九已至,卻和暖如春殖属,著一層夾襖步出監(jiān)牢的瞬間姐叁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來泰國打工洗显, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留外潜,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓挠唆,卻偏偏與公主長得像处窥,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子玄组,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 29,320評(píng)論 8 265
  • 我常常覺得家人對(duì)我的愛比我想象的還要謙卑滔驾。 我的奶奶聽到我隨口說的注意保暖的話,話筒那邊就要抽鼻子俄讹。 我的媽媽保存...
    騫翮er閱讀 256評(píng)論 0 1
  • 曾經(jīng)路過你 便是到如今也無法走近你 任憑旁人添上無數(shù)模糊筆畫 我還是喜歡那個(gè)純白色的你啊 那個(gè)溫柔淺笑的你啊 那個(gè)...
    阿火moete閱讀 123評(píng)論 0 1