Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為 SQLite 寫一個輕量 ORM:用反射完成實體與 ContentValues 的雙向轉換

編輯:關於 Android 程式設計

幾乎每個 Android App 都要碰資料庫,就算是純客戶端應用,瀏覽紀錄、收藏清單、離線快取也還是得落地。Web 端有 Hibernate 這類成熟框架,Android 上開源的 ORM 也不少,但很多時候並不想為了幾張表引入第三方依賴——那不如自己封裝一層。

先想清楚一件事:SQLite 的 CRUD 本質上就是實體物件與 ContentValues 之間的互相轉換。既然欄位名稱和 Java 欄位名稱可以對齊,那麼用反射就能自動完成這層映射,ORM 也就成型了。

DBDataHelper 核心結構

/**********************************************************
 * 檔案名稱:DBDataHelper.java
 * 檔案描述:資料庫操作助手類
 **********************************************************/
public final class DBDataHelper {

    private static DBDataHelper dataHelper = null;
    private DBHelper dbHelper = null;

    private static final String SELECT   = "select ";
    private static final String FROM     = " from ";
    private static final String WHERE    = " where ";
    private static final String ORDER_BY = " order by ";

    private DBDataHelper() {
        dbHelper = DBHelper.getInstance();
    }

    public static DBDataHelper getInstance() {
        if (dataHelper == null) {
            dataHelper = new DBDataHelper();
        }
        return dataHelper;
    }

    /**
     * 依條件查詢資料表,並直接轉成實體集合
     *
     * @param table        表名
     * @param selection    條件,例如 "id>? and name<>?",不需要可傳 null
     * @param selectionArgs 對應的參數,會逐一取代上述的 "?"
     * @param orderby      排序欄位
     * @param moduleClass  要轉成的模型類別,例如 WebPage.class
     * @return 模型集合
     */
    public ArrayList<Module> select(final String table, final String selection,
                                     final String[] selectionArgs, final String orderby,
                                     final Class<?> moduleClass) {
        SQLiteDatabase database = null;
        Cursor cursor = null;
        ArrayList<Module> moduleList = new ArrayList<Module>();
        synchronized (dbHelper) {
            try {
                database = dbHelper.getReadableDatabase();
                cursor = database.query(table, null, selection, selectionArgs, null, null, orderby, null);
                changeToList(cursor, moduleList, moduleClass);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                dbHelper.closeDatabase(database);
            }
        }
        return moduleList;
    }

    /** 依 id 更新一筆資料 */
    public long update(final String table, final Module module) {
        synchronized (dbHelper) {
            ContentValues values = moduleToContentValues(module);
            return dbHelper.update(table, values, DBHelper.ID + "=?", new String[]{ module.id });
        }
    }

    /** 依 id 刪除一筆資料 */
    public int delete(final String table, final Module module) {
        synchronized (dbHelper) {
            return dbHelper.delete(table, "id=?", new String[]{ module.id });
        }
    }
}

Cursor 轉實體

映射的關鍵在兩個私有方法。changeToList 負責遍歷 Cursor,changeToModule 則把每一列依欄位名稱塞進新物件:

private Module changeToModule(Cursor cursor, Class<?> moduleClass)
        throws IllegalAccessException, InstantiationException, SecurityException, NoSuchFieldException {
    synchronized (dbHelper) {
        String[] columnNames = cursor.getColumnNames();
        int columnCount = columnNames.length;
        Module module = (Module) moduleClass.newInstance();
        for (int j = 0; j < columnCount; j++) {
            Field field = moduleClass.getField(columnNames[j]);
            String filedValue = cursor.getString(j);
            if (filedValue != null) {
                field.set(module, filedValue.trim());
            }
        }
        return module;
    }
}

實體轉 ContentValues

反方向的轉換同樣靠反射,只是多了一道型別判斷,並用 -1 當作「未設定」的哨兵值:

private ContentValues moduleToContentValues(final Module module) {
    ContentValues values = new ContentValues();
    Field[] fields = module.getClass().getFields();
    int fieldValueForInt = -1;
    try {
        for (Field field : fields) {
            String fieldName = field.getName();
            if (field.get(module) instanceof String) {
                String fieldValue = (String) field.get(module);
                values.put(fieldName, fieldValue != null ? fieldValue.trim() : "");
            } else if (field.get(module) instanceof Integer) {
                fieldValueForInt = (Integer) field.get(module);
                if (fieldValueForInt != -1) {
                    values.put(fieldName, fieldValueForInt);
                }
            }
        }
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }
    return values;
}

這套封裝的代價

用反射換取「不必每次手寫 SQL」的開發速度,但也得接受它的限制:查詢用 getField() 只能取到 public 欄位,因此實體類別的屬性都得公開,這與一般 JavaBean 的封裝原則相衝;所有值一律以字串取出再塞回欄位,型別轉換與 field.set() 的相容性都要自己扛;而且反射本身有效能成本,大量資料列時會明顯落後於 ContentValues 直接寫入。

如果只是想理解 ORM 的原理、或專案規模不大,這樣一層薄封裝綽綽有餘;若資料表多、查詢條件複雜,還是建議改用 Room 這類有編譯期檢查的方案,把錯誤從執行期往前推到編譯期。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved