Android sqlite数据库操作通用框架AHibernate(二)-CRUD ...

贴出源代码供大家交流使用,欢迎朋友们对代码提供宝贵意见,直接写到评论中即可.

使用示例和步骤见上一篇博客:http://blog.csdn.net/lk_blog/article/details/7455992

源码和示例下载地址: http://download.csdn.net/detail/lk_blog/4222048

AHibernate1.1已经发布,下载地址: http://download.csdn.net/detail/lk_blog/4786640

(一)注解类:

Table.java

[java]  view plain copy
  1. <span style="font-size:18px;">package com.tgb.lk.ahibernate.annotation;  
  2.   
  3. import java.lang.annotation.Retention;  
  4. import java.lang.annotation.RetentionPolicy;  
  5. import java.lang.annotation.Target;  
  6.   
  7. @Retention(RetentionPolicy.RUNTIME)  
  8. @Target( { java.lang.annotation.ElementType.TYPE })  
  9. public @interface Table {  
  10.     /** 
  11.      * 表名 
  12.      *  
  13.      * @return 
  14.      */  
  15.     public abstract String name();  
  16. }</span>  

Column.java

[java]  view plain copy
  1. <span style="font-size:18px;">package com.tgb.lk.ahibernate.annotation;  
  2.   
  3. import java.lang.annotation.Retention;  
  4. import java.lang.annotation.RetentionPolicy;  
  5. import java.lang.annotation.Target;  
  6.   
  7. @Retention(RetentionPolicy.RUNTIME)  
  8. @Target( { java.lang.annotation.ElementType.FIELD })  
  9. public @interface Column {  
  10.     /** 
  11.      * 列名 
  12.      *  
  13.      * @return 
  14.      */  
  15.     public abstract String name();  
  16.   
  17.     public abstract String type() default "";  
  18.   
  19.     public abstract int length() default 0;  
  20. }</span>  
Id.java
[java]  view plain copy
  1. <span style="font-size:18px;">package com.tgb.lk.ahibernate.annotation;  
  2.   
  3. import java.lang.annotation.Retention;  
  4. import java.lang.annotation.RetentionPolicy;  
  5. import java.lang.annotation.Target;  
  6.   
  7. @Retention(RetentionPolicy.RUNTIME)  
  8. @Target( { java.lang.annotation.ElementType.FIELD })  
  9. public @interface Id {  
  10. }</span>  

(二)Util类:

TableHelper.java

[java]  view plain copy
  1. package com.tgb.lk.ahibernate.util;  
  2.   
  3. import android.database.sqlite.SQLiteDatabase;  
  4. import android.util.Log;  
  5.   
  6. import java.lang.reflect.Field;  
  7. import java.sql.Blob;  
  8. import java.util.ArrayList;  
  9. import java.util.LinkedHashMap;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import com.tgb.lk.ahibernate.annotation.Column;  
  14. import com.tgb.lk.ahibernate.annotation.Id;  
  15. import com.tgb.lk.ahibernate.annotation.Table;  
  16.   
  17. public class TableHelper {  
  18.     private static final String TAG = "AHibernate";  
  19.   
  20.     public static <T> void createTablesByClasses(SQLiteDatabase db,  
  21.             Class<?>[] clazzs) {  
  22.         for (Class<?> clazz : clazzs)  
  23.             createTable(db, clazz);  
  24.     }  
  25.   
  26.     public static <T> void dropTablesByClasses(SQLiteDatabase db,  
  27.             Class<?>[] clazzs) {  
  28.         for (Class<?> clazz : clazzs)  
  29.             dropTable(db, clazz);  
  30.     }  
  31.   
  32.     public static <T> void createTable(SQLiteDatabase db, Class<T> clazz) {  
  33.         String tableName = "";  
  34.         if (clazz.isAnnotationPresent(Table.class)) {  
  35.             Table table = (Table) clazz.getAnnotation(Table.class);  
  36.             tableName = table.name();  
  37.         }  
  38.   
  39.         StringBuilder sb = new StringBuilder();  
  40.         sb.append("CREATE TABLE ").append(tableName).append(" (");  
  41.   
  42.         List<Field> allFields = TableHelper  
  43.                 .joinFields(clazz.getDeclaredFields(), clazz.getSuperclass()  
  44.                         .getDeclaredFields());  
  45.         for (Field field : allFields) {  
  46.             if (!field.isAnnotationPresent(Column.class)) {  
  47.                 continue;  
  48.             }  
  49.   
  50.             Column column = (Column) field.getAnnotation(Column.class);  
  51.   
  52.             String columnType = "";  
  53.             if (column.type().equals(""))  
  54.                 columnType = getColumnType(field.getType());  
  55.             else {  
  56.                 columnType = column.type();  
  57.             }  
  58.   
  59.             sb.append(column.name() + " " + columnType);  
  60.   
  61.             if (column.length() != 0) {  
  62.                 sb.append("(" + column.length() + ")");  
  63.             }  
  64.   
  65.             if ((field.isAnnotationPresent(Id.class)) //update 2012-06-10  
  66.                     && ((field.getType() == Integer.TYPE) || (field.getType() == Integer.class)))  
  67.                 sb.append(" primary key autoincrement");  
  68.             else if (field.isAnnotationPresent(Id.class)) {  
  69.                 sb.append(" primary key");  
  70.             }  
  71.   
  72.             sb.append(", ");  
  73.         }  
  74.   
  75.         sb.delete(sb.length() - 2, sb.length() - 1);  
  76.         sb.append(")");  
  77.   
  78.         String sql = sb.toString();  
  79.   
  80.         Log.d(TAG, "crate table [" + tableName + "]: " + sql);  
  81.   
  82.         db.execSQL(sql);  
  83.     }  
  84.   
  85.     public static <T> void dropTable(SQLiteDatabase db, Class<T> clazz) {  
  86.         String tableName = "";  
  87.         if (clazz.isAnnotationPresent(Table.class)) {  
  88.             Table table = (Table) clazz.getAnnotation(Table.class);  
  89.             tableName = table.name();  
  90.         }  
  91.         String sql = "DROP TABLE IF EXISTS " + tableName;  
  92.         Log.d(TAG, "dropTable[" + tableName + "]:" + sql);  
  93.         db.execSQL(sql);  
  94.     }  
  95.   
  96.     private static String getColumnType(Class<?> fieldType) {  
  97.         if (String.class == fieldType) {  
  98.             return "TEXT";  
  99.         }  
  100.         if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {  
  101.             return "INTEGER";  
  102.         }  
  103.         if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {  
  104.             return "BIGINT";  
  105.         }  
  106.         if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {  
  107.             return "FLOAT";  
  108.         }  
  109.         if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {  
  110.             return "INT";  
  111.         }  
  112.         if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {  
  113.             return "DOUBLE";  
  114.         }  
  115.         if (Blob.class == fieldType) {  
  116.             return "BLOB";  
  117.         }  
  118.   
  119.         return "TEXT";  
  120.     }  
  121.   
  122.     // 合并Field数组并去重,并实现过滤掉非Column字段,和实现Id放在首字段位置功能  
  123.     public static List<Field> joinFields(Field[] fields1, Field[] fields2) {  
  124.         Map<String, Field> map = new LinkedHashMap<String, Field>();  
  125.         for (Field field : fields1) {  
  126.             // 过滤掉非Column定义的字段  
  127.             if (!field.isAnnotationPresent(Column.class)) {  
  128.                 continue;  
  129.             }  
  130.             Column column = (Column) field.getAnnotation(Column.class);  
  131.             map.put(column.name(), field);  
  132.         }  
  133.         for (Field field : fields2) {  
  134.             // 过滤掉非Column定义的字段  
  135.             if (!field.isAnnotationPresent(Column.class)) {  
  136.                 continue;  
  137.             }  
  138.             Column column = (Column) field.getAnnotation(Column.class);  
  139.             if (!map.containsKey(column.name())) {  
  140.                 map.put(column.name(), field);  
  141.             }  
  142.         }  
  143.         List<Field> list = new ArrayList<Field>();  
  144.         for (String key : map.keySet()) {  
  145.             Field tempField = map.get(key);  
  146.             // 如果是Id则放在首位置.  
  147.             if (tempField.isAnnotationPresent(Id.class)) {  
  148.                 list.add(0, tempField);  
  149.             } else {  
  150.                 list.add(tempField);  
  151.             }  
  152.         }  
  153.         return list;  
  154.     }  
  155. }  



MyDBHelper.java

[java]  view plain copy
  1. <span style="font-size:18px;">package com.tgb.lk.ahibernate.util;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class MyDBHelper extends SQLiteOpenHelper {  
  8.     private Class<?>[] modelClasses;  
  9.   
  10.     public MyDBHelper(Context context, String databaseName,  
  11.             SQLiteDatabase.CursorFactory factory, int databaseVersion,  
  12.             Class<?>[] modelClasses) {  
  13.         super(context, databaseName, factory, databaseVersion);  
  14.         this.modelClasses = modelClasses;  
  15.     }  
  16.   
  17.     public void onCreate(SQLiteDatabase db) {  
  18.         TableHelper.createTablesByClasses(db, this.modelClasses);  
  19.     }  
  20.   
  21.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  22.         TableHelper.dropTablesByClasses(db, this.modelClasses);  
  23.         onCreate(db);  
  24.     }  
  25. }</span>  
(三)接口和实现:

BaseDao.java

[java]  view plain copy
  1. <span style="font-size:18px;">package com.tgb.lk.ahibernate.dao;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7.   
  8. public interface BaseDao<T> {  
  9.   
  10.     public SQLiteOpenHelper getDbHelper();  
  11.       
  12.     public abstract long insert(T entity);  
  13.       
  14.     public abstract void delete(int id);  
  15.       
  16.     public abstract void delete(Integer... ids);  
  17.   
  18.     public abstract void update(T entity);  
  19.   
  20.     public abstract T get(int id);  
  21.   
  22.     public abstract List<T> rawQuery(String sql, String[] selectionArgs);  
  23.   
  24.     public abstract List<T> find();  
  25.   
  26.     public abstract List<T> find(String[] columns, String selection,  
  27.             String[] selectionArgs, String groupBy, String having,  
  28.             String orderBy, String limit);  
  29.   
  30.     public abstract boolean isExist(String sql, String[] selectionArgs);  
  31.   
  32.     /** 
  33.      * 将查询的结果保存为名值对map. 
  34.      *  
  35.      * @param sql 
  36.      *            查询sql 
  37.      * @param selectionArgs 
  38.      *            参数值 
  39.      * @return 返回的Map中的key全部是小写形式. 
  40.      */  
  41.     public List<Map<String, String>> query2MapList(String sql,  
  42.             String[] selectionArgs);  
  43.       
  44.     /** 
  45.      * 封装执行sql代码. 
  46.      * @param sql 
  47.      * @param selectionArgs 
  48.      */  
  49.     public void execSql(String sql, Object[] selectionArgs);  
  50.   
  51. }</span>  

BaseDaoImpl.java

[java]  view plain copy
  1. package com.tgb.lk.ahibernate.dao.impl;  
  2.   
  3. import android.content.ContentValues;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7. import android.util.Log;  
  8. import java.lang.reflect.Field;  
  9. import java.sql.Blob;  
  10. import java.util.ArrayList;  
  11. import java.util.Date;  
  12. import java.util.HashMap;  
  13. import java.util.List;  
  14. import java.util.Map;  
  15.   
  16. import com.tgb.lk.ahibernate.annotation.Column;  
  17. import com.tgb.lk.ahibernate.annotation.Id;  
  18. import com.tgb.lk.ahibernate.annotation.Table;  
  19. import com.tgb.lk.ahibernate.dao.BaseDao;  
  20. import com.tgb.lk.ahibernate.util.TableHelper;  
  21.   
  22. /** 
  23.  * AHibernate概要 <br/> 
  24.  * (一)支持功能: 1.自动建表,支持属性来自继承类:可根据注解自动完成建表,并且对于继承类中的注解字段也支持自动建表. 2.自动支持增删改 
  25.  * ,增改支持对象化操作:增删改是数据库操作的最基本单元,不用重复写这些增删改的代码,并且添加和更新支持类似于hibernate中的对象化操作. 
  26.  * 3.查询方式灵活:支持android框架提供的方式,也支持原生sql方式. 
  27.  * 4.查询结果对象化:对于查询结果可自动包装为实体对象,类似于hibernate框架. 
  28.  * 5.查询结果灵活:查询结果支持对象化,也支持结果为List<Map<String,String>>形式,这个方法在实际项目中很实用,且效率更好些. 
  29.  * 6.日志较详细:因为android开发不支持热部署调试,运行报错时可根据日志来定位错误,这样可以减少运行Android的次数. <br/> 
  30.  * (二)不足之处: <br/> 
  31.  * 1.id暂时只支持int类型,不支持uuid,在sqlite中不建议用uuid. 
  32.  * 2.现在每个方法都自己开启和关闭事务,暂时还不支持在一个事务中做多个操作然后统一提交事务. <br/> 
  33.  * (三)作者寄语:<br/> 
  34.  * 昔日有JavaScript借Java发展,今日也希望AHibernate借Hibernate之名发展. 
  35.  * 希望这个项目以后会成为开源社区的重要一员,更希望这个项目能给所有Android开发者带便利. 
  36.  * 欢迎访问我的博客:http://blog.csdn.net/lk_blog, 
  37.  * 这里有这个框架的使用范例和源码,希望朋友们多多交流完善这个框架,共同推动中国开源事业的发展,AHibernate期待与您共创美好未来!!! 
  38.  */  
  39. public class BaseDaoImpl<T> implements BaseDao<T> {  
  40.     private String TAG = "AHibernate";  
  41.     private SQLiteOpenHelper dbHelper;  
  42.     private String tableName;  
  43.     private String idColumn;  
  44.     private Class<T> clazz;  
  45.     private List<Field> allFields;  
  46.   
  47.     public BaseDaoImpl(SQLiteOpenHelper dbHelper) {  
  48.         this.dbHelper = dbHelper;  
  49.   
  50.         this.clazz = ((Class<T>) ((java.lang.reflect.ParameterizedType) super  
  51.                 .getClass().getGenericSuperclass()).getActualTypeArguments()[0]);  
  52.   
  53.         if (this.clazz.isAnnotationPresent(Table.class)) {  
  54.             Table table = (Table) this.clazz.getAnnotation(Table.class);  
  55.             this.tableName = table.name();  
  56.         }  
  57.   
  58.         // 加载所有字段  
  59.         this.allFields = TableHelper.joinFields(this.clazz.getDeclaredFields(),  
  60.                 this.clazz.getSuperclass().getDeclaredFields());  
  61.   
  62.         // 找到主键  
  63.         for (Field field : this.allFields) {  
  64.             if (field.isAnnotationPresent(Id.class)) {  
  65.                 Column column = (Column) field.getAnnotation(Column.class);  
  66.                 this.idColumn = column.name();  
  67.                 break;  
  68.             }  
  69.         }  
  70.   
  71.         Log.d(TAG, "clazz:" + this.clazz + " tableName:" + this.tableName  
  72.                 + " idColumn:" + this.idColumn);  
  73.     }  
  74.   
  75.     public SQLiteOpenHelper getDbHelper() {  
  76.         return dbHelper;  
  77.     }  
  78.   
  79.     public T get(int id) {  
  80.         String selection = this.idColumn + " = ?";  
  81.         String[] selectionArgs = { Integer.toString(id) };  
  82.         Log.d(TAG, "[get]: select * from " + this.tableName + " where "  
  83.                 + this.idColumn + " = '" + id + "'");  
  84.         List<T> list = find(null, selection, selectionArgs, nullnullnull,  
  85.                 null);  
  86.         if ((list != null) && (list.size() > 0)) {  
  87.             return (T) list.get(0);  
  88.         }  
  89.         return null;  
  90.     }  
  91.   
  92.     public List<T> rawQuery(String sql, String[] selectionArgs) {  
  93.         Log.d(TAG, "[rawQuery]: " + sql);  
  94.   
  95.         List<T> list = new ArrayList<T>();  
  96.         SQLiteDatabase db = null;  
  97.         Cursor cursor = null;  
  98.         try {  
  99.             db = this.dbHelper.getReadableDatabase();  
  100.             cursor = db.rawQuery(sql, selectionArgs);  
  101.   
  102.             getListFromCursor(list, cursor);  
  103.         } catch (Exception e) {  
  104.             Log.e(this.TAG, "[rawQuery] from DB Exception.");  
  105.             e.printStackTrace();  
  106.         } finally {  
  107.             if (cursor != null) {  
  108.                 cursor.close();  
  109.             }  
  110.             if (db != null) {  
  111.                 db.close();  
  112.             }  
  113.         }  
  114.   
  115.         return list;  
  116.     }  
  117.   
  118.     public boolean isExist(String sql, String[] selectionArgs) {  
  119.         Log.d(TAG, "[isExist]: " + sql);  
  120.   
  121.         SQLiteDatabase db = null;  
  122.         Cursor cursor = null;  
  123.         try {  
  124.             db = this.dbHelper.getReadableDatabase();  
  125.             cursor = db.rawQuery(sql, selectionArgs);  
  126.             if (cursor.getCount() > 0) {  
  127.                 return true;  
  128.             }  
  129.         } catch (Exception e) {  
  130.             Log.e(this.TAG, "[isExist] from DB Exception.");  
  131.             e.printStackTrace();  
  132.         } finally {  
  133.             if (cursor != null) {  
  134.                 cursor.close();  
  135.             }  
  136.             if (db != null) {  
  137.                 db.close();  
  138.             }  
  139.         }  
  140.         return false;  
  141.     }  
  142.   
  143.     public List<T> find() {  
  144.         return find(nullnullnullnullnullnullnull);  
  145.     }  
  146.   
  147.     public List<T> find(String[] columns, String selection,  
  148.             String[] selectionArgs, String groupBy, String having,  
  149.             String orderBy, String limit) {  
  150.         Log.d(TAG, "[find]");  
  151.   
  152.         List<T> list = new ArrayList<T>();  
  153.         SQLiteDatabase db = null;  
  154.         Cursor cursor = null;  
  155.         try {  
  156.             db = this.dbHelper.getReadableDatabase();  
  157.             cursor = db.query(this.tableName, columns, selection,  
  158.                     selectionArgs, groupBy, having, orderBy, limit);  
  159.   
  160.             getListFromCursor(list, cursor);  
  161.         } catch (Exception e) {  
  162.             Log.e(this.TAG, "[find] from DB Exception");  
  163.             e.printStackTrace();  
  164.         } finally {  
  165.             if (cursor != null) {  
  166.                 cursor.close();  
  167.             }  
  168.             if (db != null) {  
  169.                 db.close();  
  170.             }  
  171.         }  
  172.   
  173.         return list;  
  174.     }  
  175.   
  176.     private void getListFromCursor(List<T> list, Cursor cursor)  
  177.             throws IllegalAccessException, InstantiationException {  
  178.         while (cursor.moveToNext()) {  
  179.             T entity = this.clazz.newInstance();  
  180.   
  181.             for (Field field : this.allFields) {  
  182.                 Column column = null;  
  183.                 if (field.isAnnotationPresent(Column.class)) {  
  184.                     column = (Column) field.getAnnotation(Column.class);  
  185.   
  186.                     field.setAccessible(true);  
  187.                     Class<?> fieldType = field.getType();  
  188.   
  189.                     int c = cursor.getColumnIndex(column.name());  
  190.                     if (c < 0) {  
  191.                         continue// 如果不存则循环下个属性值  
  192.                     } else if ((Integer.TYPE == fieldType)  
  193.                             || (Integer.class == fieldType)) {  
  194.                         field.set(entity, cursor.getInt(c));  
  195.                     } else if (String.class == fieldType) {  
  196.                         field.set(entity, cursor.getString(c));  
  197.                     } else if ((Long.TYPE == fieldType)  
  198.                             || (Long.class == fieldType)) {  
  199.                         field.set(entity, Long.valueOf(cursor.getLong(c)));  
  200.                     } else if ((Float.TYPE == fieldType)  
  201.                             || (Float.class == fieldType)) {  
  202.                         field.set(entity, Float.valueOf(cursor.getFloat(c)));  
  203.                     } else if ((Short.TYPE == fieldType)  
  204.                             || (Short.class == fieldType)) {  
  205.                         field.set(entity, Short.valueOf(cursor.getShort(c)));  
  206.                     } else if ((Double.TYPE == fieldType)  
  207.                             || (Double.class == fieldType)) {  
  208.                         field.set(entity, Double.valueOf(cursor.getDouble(c)));  
  209.                     } else if (Blob.class == fieldType) {  
  210.                         field.set(entity, cursor.getBlob(c));  
  211.                     } else if (Date.class == fieldType) {// 处理java.util.Date类型,update 2012-06-10  
  212.                         Date date = new Date();  
  213.                         date.setTime(cursor.getLong(c));  
  214.                         field.set(entity, date);  
  215.                     } else if (Character.TYPE == fieldType) {  
  216.                         String fieldValue = cursor.getString(c);  
  217.   
  218.                         if ((fieldValue != null) && (fieldValue.length() > 0)) {  
  219.                             field.set(entity, Character.valueOf(fieldValue  
  220.                                     .charAt(0)));  
  221.                         }  
  222.                     }  
  223.                 }  
  224.             }  
  225.   
  226.             list.add((T) entity);  
  227.         }  
  228.     }  
  229.   
  230.     public long insert(T entity) {  
  231.         Log.d(TAG, "[insert]: inset into " + this.tableName + " "  
  232.                 + entity.toString());  
  233.         SQLiteDatabase db = null;  
  234.         try {  
  235.             db = this.dbHelper.getWritableDatabase();  
  236.             ContentValues cv = new ContentValues();  
  237.             setContentValues(entity, cv, "create");  
  238.             long row = db.insert(this.tableName, null, cv);  
  239.             return row;  
  240.         } catch (Exception e) {  
  241.             Log.d(this.TAG, "[insert] into DB Exception.");  
  242.             e.printStackTrace();  
  243.         } finally {  
  244.             if (db != null) {  
  245.                 db.close();  
  246.             }  
  247.         }  
  248.   
  249.         return 0L;  
  250.     }  
  251.   
  252.     public void delete(int id) {  
  253.         SQLiteDatabase db = this.dbHelper.getWritableDatabase();  
  254.         String where = this.idColumn + " = ?";  
  255.         String[] whereValue = { Integer.toString(id) };  
  256.   
  257.         Log.d(TAG, "[delete]: delelte from " + this.tableName + " where "  
  258.                 + where.replace("?", String.valueOf(id)));  
  259.   
  260.         db.delete(this.tableName, where, whereValue);  
  261.         db.close();  
  262.     }  
  263.   
  264.     public void delete(Integer... ids) {  
  265.         if (ids.length > 0) {  
  266.             StringBuffer sb = new StringBuffer();  
  267.             for (int i = 0; i < ids.length; i++) {  
  268.                 sb.append('?').append(',');  
  269.             }  
  270.             sb.deleteCharAt(sb.length() - 1);  
  271.             SQLiteDatabase db = this.dbHelper.getWritableDatabase();  
  272.             String sql = "delete from " + this.tableName + " where "  
  273.                     + this.idColumn + " in (" + sb + ")";  
  274.   
  275.             Log.d(TAG, "[delete]: " + sql);  
  276.   
  277.             db.execSQL(sql, (Object[]) ids);  
  278.             db.close();  
  279.         }  
  280.     }  
  281.   
  282.     public void update(T entity) {  
  283.         SQLiteDatabase db = null;  
  284.         try {  
  285.             db = this.dbHelper.getWritableDatabase();  
  286.             ContentValues cv = new ContentValues();  
  287.   
  288.             setContentValues(entity, cv, "update");  
  289.   
  290.             String where = this.idColumn + " = ?";  
  291.             int id = Integer.parseInt(cv.get(this.idColumn).toString());  
  292.             cv.remove(this.idColumn);  
  293.   
  294.             Log.d(TAG, "[update]: update " + this.tableName + " where "  
  295.                     + where.replace("?", String.valueOf(id)));  
  296.   
  297.             String[] whereValue = { Integer.toString(id) };  
  298.             db.update(this.tableName, cv, where, whereValue);  
  299.         } catch (Exception e) {  
  300.             Log.d(this.TAG, "[update] DB Exception.");  
  301.             e.printStackTrace();  
  302.         } finally {  
  303.             if (db != null)  
  304.                 db.close();  
  305.         }  
  306.     }  
  307.   
  308.     private void setContentValues(T entity, ContentValues cv, String type)  
  309.             throws IllegalAccessException {  
  310.   
  311.         for (Field field : this.allFields) {  
  312.             if (!field.isAnnotationPresent(Column.class)) {  
  313.                 continue;  
  314.             }  
  315.             Column column = (Column) field.getAnnotation(Column.class);  
  316.   
  317.             field.setAccessible(true);  
  318.             Object fieldValue = field.get(entity);  
  319.             if (fieldValue == null)  
  320.                 continue;  
  321.             if (("create".equals(type))  
  322.                     && (field.isAnnotationPresent(Id.class))) {  
  323.                 continue;  
  324.             }  
  325.             if (Date.class == field.getType()) {// 处理java.util.Date类型,update 2012-06-10  
  326.                 cv.put(column.name(), ((Date) fieldValue).getTime());  
  327.                 continue;  
  328.             }  
  329.             cv.put(column.name(), fieldValue.toString());  
  330.         }  
  331.     }  
  332.   
  333.     /** 
  334.      * 将查询的结果保存为名值对map. 
  335.      *  
  336.      * @param sql 
  337.      *            查询sql 
  338.      * @param selectionArgs 
  339.      *            参数值 
  340.      * @return 返回的Map中的key全部是小写形式. 
  341.      */  
  342.     public List<Map<String, String>> query2MapList(String sql,  
  343.             String[] selectionArgs) {  
  344.         Log.d(TAG, "[query2MapList]: " + sql);  
  345.         SQLiteDatabase db = null;  
  346.         Cursor cursor = null;  
  347.         List<Map<String, String>> retList = new ArrayList<Map<String, String>>();  
  348.         try {  
  349.             db = this.dbHelper.getReadableDatabase();  
  350.             cursor = db.rawQuery(sql, selectionArgs);  
  351.             while (cursor.moveToNext()) {  
  352.                 Map<String, String> map = new HashMap<String, String>();  
  353.                 for (String columnName : cursor.getColumnNames()) {  
  354.                     map.put(columnName.toLowerCase(), cursor.getString(cursor  
  355.                             .getColumnIndex(columnName)));  
  356.                 }  
  357.                 retList.add(map);  
  358.             }  
  359.         } catch (Exception e) {  
  360.             Log.e(TAG, "[query2MapList] from DB exception");  
  361.             e.printStackTrace();  
  362.         } finally {  
  363.             if (cursor != null) {  
  364.                 cursor.close();  
  365.             }  
  366.             if (db != null) {  
  367.                 db.close();  
  368.             }  
  369.         }  
  370.   
  371.         return retList;  
  372.     }  
  373.   
  374.     /** 
  375.      * 返回查询结果的Cursor 
  376.      *  
  377.      * @param sql 
  378.      *            查询sql 
  379.      * @param selectionArgs 
  380.      *            参数值 
  381.      * @return cursor 
  382.      */  
  383.     public Cursor query2Cursor(String sql, String[] selectionArgs) {  
  384.         Log.d(TAG, "[query2Cursor]: " + sql);  
  385.         SQLiteDatabase db = null;  
  386.         Cursor cursor = null;  
  387.         try {  
  388.             db = this.dbHelper.getReadableDatabase();  
  389.             cursor = db.rawQuery(sql, selectionArgs);  
  390.             return cursor;  
  391.         } catch (Exception e) {  
  392.             Log.e(TAG, "[query2Cursor] from DB exception");  
  393.             e.printStackTrace();  
  394.         } finally {  
  395.             // if (cursor != null) {  
  396.             // cursor.close();  
  397.             // }  
  398.             if (db != null) {  
  399.                 db.close();  
  400.             }  
  401.         }  
  402.   
  403.         return cursor;  
  404.     }  
  405.   
  406.     /** 
  407.      * 封装执行sql代码. 
  408.      *  
  409.      * @param sql 
  410.      * @param selectionArgs 
  411.      */  
  412.     public void execSql(String sql, Object[] selectionArgs) {  
  413.         SQLiteDatabase db = null;  
  414.         Log.d(TAG, "[execSql]: " + sql);  
  415.         try {  
  416.             db = this.dbHelper.getWritableDatabase();  
  417.             if (selectionArgs == null) {  
  418.                 db.execSQL(sql);  
  419.             } else {  
  420.                 db.execSQL(sql, selectionArgs);  
  421.             }  
  422.         } catch (Exception e) {  
  423.             Log.e(TAG, "[execSql] DB exception.");  
  424.             e.printStackTrace();  
  425.         } finally {  
  426.             if (db != null) {  
  427.                 db.close();  
  428.             }  
  429.         }  
  430.     }  
  431. }  



转载请注明原文出处: http://blog.csdn.net/lk_blog/article/details/7456125
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/** * YDL_Hibernate概要 <br/> * (一)支持功能: 1.自动建表,支持属性来自继承类:可根据注解自动完成建表,并且对于继承类中的注解字段也支持自动建表. 2.自动支持增删改 * ,增改支持对象化操作:增删改是数据库操作的最基本单元,不用重复写这些增删改的代码,并且添加和更新支持类似于hibernate中的对象化操作. * 3.查询方式灵活:支持android框架提供的方式,也支持原生sql方式. * 4.查询结果对象化:对于查询结果可自动包装为实体对象,类似于hibernate框架. * 5.查询结果灵活:查询结果支持对象化,也支持结果为List<Map<String,String>>形式,这个方法在实际项目中很实用,且效率更好些. * 6.日志较详细:因为android开发不支持热部署调试,运行报错时可根据日志来定位错误,这样可以减少运行Android的次数. <br/> * ()不足之处: <br/> * 1.id暂时只支持int类型,不支持uuid,在sqlite中不建议用uuid. * 2.现在每个方法都自己开启和关闭事务,暂时还不支持在一个事务中做多个操作然后统一提交事务. <br/> * (三)作者寄语:<br/> * 昔日有JavaScript借Java发展,今日也希望AHibernateHibernate之名发展. * 希望这个项目以后会成为开源社区的重要一员,更希望这个项目能给所有Android开发者带便利. * 欢迎访问我的博客:http://blog.csdn.net/linglongxin24, * 这里有这个框架的使用范例和源码,希望朋友们多多交流完善这个框架,共同推动中国开源事业的发展,YDL_Hibernate期待与您共创美好未来!!! */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值