【傳智播客鄭州校區分享】資料庫框架詳解
阿新 • • 發佈:2019-01-05
- // 問題二:如何設定實體中的資料到資料庫的表中對應的列上
- public void setValues(M m, ContentValues values) {
- // values.put(DBHelper.TABLE_NEWS_TITLE, news.getTitle());
- // 資料庫表中列的資訊與實體中欄位的對應關係
- Field[] fields = m.getClass().getDeclaredFields();// 10個20個
- for (Field item : fields) {
- item.setAccessible(true);// 暴力反射
- Column column = item.getAnnotation(Column.class);
- if (column != null) {
- String key = column.value();
- // 遺留問題:關於主鍵+自增,如果是自增的,需要交由系統區設定資料
- ID id = item.getAnnotation(ID.class);
- if (id != null) {
- if (id.autoincrement()) {
- // 需要交由系統區設定資料
- } else {
- try {
- String value = item.get(m).toString();// m.title
- values.put(key, value);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- } else {
- try {
- String value = item.get(m).toString();// m.title
- values.put(key, value);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
}