android sqlite数据库封装 实现crud

android常用的数据保存方式有文件、sharepreferences、数据库、网络、contentprovider集中方式。

       文件存储方式,经常使用在缓存整个页面数据,比如电子书内容、html数据等。

       sharepreferrences存储方式,实质也就是xml文件存储的封装,常用于存储配置参数数据。当然也可以用文件存储+Properties来存储参数数据。

       网络,就是将数据存储在网络空间上。

        contentprovider主要作用是统一数据存储方式,实现数据共享,以后有机会仔细分析下。

        数据库的方式,常用在存储一系列的结构复杂的数据,轻量级的数据库SQlit使用起来还是比较简单,但是总想能像hibernate似的框架可以进行下封装,实现orm并且可以实现简单的rcud。这里就介绍下一个分装过程,源码下载在后面。

 一、封装数据库的类结构

 

结构比较简单:BaseBean.java--实体类的基类

                       DBConfig.java---数据库的参数,包括数据库名、要创建的表列表、数据库版本等

                       IssContentProvider.java--继承了ContentProvider,定义了数据库的初始化和操作

                       DBFactory--数据库工厂类

                       Table.java----定义Table的annotation

                       TableColumn.java--定义表的列的annotation和属性

                       TableUtil.java--书库操作工具类,主要是获得表和根据标签拼装sql语句

二、封装数据库的使用过程

    由于封装后的数据库使用比较简单,就跟配置好hibernate之后使用似的,所以咱们先看下咱们使用,不理解的地方,等分析了整个实现过程后就行清晰了。

     1、要实现orm,肯定要定义带标签的实体类,当然是继承BaseBean类。

     2、要将数据库参数传递给DBConfig,并初始化。

     3、数据库操作类,通过contentprovideder实现crud。

用例子看下
1,定义实体类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class SmartDownloadBean extends BaseBean<SmartDownloadBean> {  
  2.   
  3.     @TableColumn(type = TableColumn.Types.TEXT, isIndex = true, isNotNull = true)  
  4.     public String downpath;  
  5.   
  6.     @TableColumn(type = TableColumn.Types.INTEGER)  
  7.     public int threadid;  
  8.       
  9.     @TableColumn(type = TableColumn.Types.INTEGER)  
  10.     public int downlength;  
  11.       
  12.     @Override  
  13.     public SmartDownloadBean parseJSON(JSONObject jsonObj) {  
  14.         return null;  
  15.     }  
  16.   
  17.     @Override  
  18.     public JSONObject toJSON() {  
  19.         // TODO Auto-generated method stub  
  20.         return null;  
  21.     }  
  22.   
  23.     @Override  
  24.     public SmartDownloadBean cursorToBean(Cursor cursor) {  
  25.         this.downpath = cursor.getString(cursor.getColumnIndex("downpath"));  
  26.         this.threadid = cursor.getInt(cursor.getColumnIndex("threadid"));  
  27.         this.downlength = cursor.getInt(cursor.getColumnIndex("downlength"));  
  28.         return this;  
  29.     }  
  30.   
  31.     @Override  
  32.     public ContentValues beanToValues() {  
  33.         ContentValues values = new ContentValues();  
  34.         if (!TextUtils.isEmpty(downpath)) {  
  35.             values.put("downpath", downpath);  
  36.         }  
  37.         if (!TextUtils.isEmpty(threadid+"")) {  
  38.             values.put("threadid", threadid);  
  39.         }  
  40.         if (!TextUtils.isEmpty(downlength+"")) {  
  41.             values.put("downlength", downlength);  
  42.         }  
  43.         return values;  
  44.     }  
  45.   
  46. }  

实体类通过标签,定义了对应表的列名、及列的属性

2、定义要创建的表、数据名等参数

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.  * 数据库配置 
  3.  **/  
  4. public class SssProvider extends IssContentProvider {  
  5.   
  6.     @Override  
  7.     public void init() {  
  8.   
  9.         // 数据库相关参数设置  
  10.         DBConfig config = new DBConfig.Builder()  
  11.                 .addTatble(SmartDownloadBean.class)  
  12.                 .setName("sss.db").setVersion(2)  
  13.                 .setAuthority("com.sss").build();  
  14.   
  15.         IssDBFactory.init(getContext(), config);  
  16.     }  
  17.   
  18.       
  19.       
  20.   
  21. }  

要定义都个表的话,再addTatble(Bean.class)即可。

3、调用数据库的工具类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.  * 操作数据库的utils 
  3.  *  
  4.  * @author dllik 2013-11-23 
  5.  */  
  6. public class DBUtils {  
  7.   
  8.     public static Uri URI_SMARTDOWNLOAD = IssContentProvider.buildUri(SmartDownloadBean.class);  
  9.   
  10.   
  11.   
  12.     /** 
  13.      * 获取每条线程已经下载的文件长度 
  14.      *  
  15.      * @param context 
  16.      * @param downpath 
  17.      * @return 
  18.      */  
  19.     public static Map<Integer, Integer> querySmartDownData(Context context, String downpath) {  
  20.         ContentResolver mResolver = context.getContentResolver();  
  21.         Cursor cursor = mResolver.query(URI_SMARTDOWNLOAD, null, "downpath=?", new String[] {  
  22.             downpath  
  23.         }, null);  
  24.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  25.         while (cursor.moveToNext()) {  
  26.             SmartDownloadBean bean = new SmartDownloadBean();  
  27.             bean.cursorToBean(cursor);  
  28.             data.put(bean.threadid, bean.downlength);  
  29.         }  
  30.         cursor.close();  
  31.         return data;  
  32.     }  
  33.   
  34.     /** 
  35.      * 保存每条线程已经下载的文件长度 
  36.      *  
  37.      * @param context 
  38.      * @param path 
  39.      * @param map 
  40.      */  
  41.     public static void insertSmartDown(Context context, String path, Map<Integer, Integer> map) {  
  42.         ContentResolver mResolver = context.getContentResolver();  
  43.         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  44.             SmartDownloadBean bean = new SmartDownloadBean();  
  45.             bean.downpath = path;  
  46.             bean.downlength = entry.getValue();  
  47.             bean.threadid = entry.getKey();  
  48.             mResolver.insert(URI_SMARTDOWNLOAD, bean.beanToValues());  
  49.         }  
  50.     }  
  51.   
  52.     /** 
  53.      * 实时更新每条线程已经下载的文件长度 
  54.      *  
  55.      * @param context 
  56.      * @param path 
  57.      * @param map 
  58.      */  
  59.     public static void updateSmartDown(Context context, String path, Map<Integer, Integer> map) {  
  60.         ContentResolver mResolver = context.getContentResolver();  
  61.         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  62.             SmartDownloadBean bean = new SmartDownloadBean();  
  63.             bean.downpath = path;  
  64.             bean.downlength = entry.getValue();  
  65.             bean.threadid = entry.getKey();  
  66.             mResolver.update(URI_SMARTDOWNLOAD, bean.beanToValues(), "downpath=? and threadid=?",  
  67.                     new String[] {  
  68.                             bean.downpath, bean.threadid + ""  
  69.                     });  
  70.         }  
  71.     }  
  72.   
  73.     /** 
  74.      * 当文件下载完成后,删除对应的下载记录 
  75.      *  
  76.      * @param context 
  77.      * @param path 
  78.      */  
  79.     public static void deleteSmartDown(Context context, String path) {  
  80.         ContentResolver mResolver = context.getContentResolver();  
  81.         mResolver.delete(URI_SMARTDOWNLOAD, "downpath=?", new String[] {  
  82.             path  
  83.         });  
  84.     }  
  85.   
  86.      
  87.   
  88. }  

三、数据库的封装过程

    看下实体类的基类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public abstract class BaseBean<T> implements Serializable {  
  2.     private static final long serialVersionUID = -804757173578073135L;  
  3.   
  4.     @TableColumn(type = TableColumn.Types.INTEGER, isPrimary = true)  
  5.     public static final String _ID = "_id";  
  6.   
  7.     /** 
  8.      * 将json对象转化为Bean实例 
  9.      * 
  10.      * @param jsonObj 
  11.      * @return 
  12.      */  
  13.     public abstract T parseJSON(JSONObject jsonObj);  
  14.   
  15.     /** 
  16.      * 将Bean实例转化为json对象 
  17.      * 
  18.      * @return 
  19.      */  
  20.     public abstract JSONObject toJSON();  
  21.   
  22.     /** 
  23.      * 将数据库的cursor转化为Bean实例(如果对象涉及在数据库存取,需实现此方法) 
  24.      * 
  25.      * @param cursor 
  26.      * @return 
  27.      */  
  28.     public abstract T cursorToBean(Cursor cursor);  
  29.   
  30.     /** 
  31.      * 将Bean实例转化为一个ContentValues实例,供存入数据库使用(如果对象涉及在数据库存取,需实现此方法) 
  32.      * 
  33.      * @return 
  34.      */  
  35.     public abstract ContentValues beanToValues();  
  36.   
  37.     @SuppressWarnings("unchecked")  
  38.     public T parseJSON(Gson gson, String json) {  
  39.         return (T) gson.fromJson(json, this.getClass());  
  40.     }  
  41.   
  42.     public ContentValues toValues() {  
  43.         ContentValues values = new ContentValues();  
  44.         try {  
  45.             Class<?> c = getClass();  
  46.             Field[] fields = c.getFields();  
  47.             for (Field f : fields) {  
  48.                 f.setAccessible(true);  
  49.                 final TableColumn tableColumnAnnotation = f.getAnnotation(TableColumn.class);  
  50.                 if (tableColumnAnnotation != null) {  
  51.                     if (tableColumnAnnotation.type() == TableColumn.Types.INTEGER) {  
  52.                         values.put(f.getName(), f.getInt(this));  
  53.                     } else if (tableColumnAnnotation.type() == TableColumn.Types.BLOB) {  
  54.                         values.put(f.getName(), (byte[]) f.get(this));  
  55.                     } else if (tableColumnAnnotation.type() == TableColumn.Types.TEXT) {  
  56.                         values.put(f.getName(), f.get(this).toString());  
  57.                     } else {  
  58.                         values.put(f.getName(), f.get(this).toString());  
  59.                     }  
  60.                 }  
  61.             }  
  62.         } catch (IllegalArgumentException e) {  
  63.             e.printStackTrace();  
  64.         } catch (IllegalAccessException e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.         return values;  
  68.     }  
  69.   
  70.   
  71. }  

说明几点:1、用到了泛型,因为定义的数据实体类有多个

                 2、实现序列化,实体类数据通过Intent进行传递

                 3、定义了一个主键id

数据库参数类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class DBConfig {  
  2.     final ArrayList<Class<? extends BaseBean<?>>> tableList;  
  3.   
  4.     final String dbName;  
  5.   
  6.     final int dbVersion;  
  7.       
  8.     final String authority;  
  9.       
  10.     final ArrayList<String> tableNameList;  
  11.   
  12.     private DBConfig(final Builder builder) {  
  13.         tableList = builder.tableList;  
  14.         dbName = builder.dbName;  
  15.         dbVersion = builder.dbVersion;  
  16.         authority = builder.authority;  
  17.           
  18.         tableNameList =  new ArrayList<String>();  
  19.         for(Class<? extends BaseBean<?>> c:tableList){  
  20.             String name = TableUtil.getTableName(c);  
  21.             tableNameList.add(name);  
  22.         }  
  23.     }  
  24.   
  25.     public static class Builder {  
  26.         private ArrayList<Class<? extends BaseBean<?>>> tableList;  
  27.   
  28.         private String dbName;  
  29.   
  30.         private int dbVersion;  
  31.           
  32.         private String authority = "com.iss.mobile";  
  33.   
  34.         public Builder() {  
  35.             tableList = new ArrayList<Class<? extends BaseBean<?>>>();  
  36.         }  
  37.   
  38.         public Builder setName(String name) {  
  39.             dbName = name;  
  40.             return this;  
  41.         }  
  42.   
  43.         public Builder setVersion(int version) {  
  44.             dbVersion = version;  
  45.             return this;  
  46.         }  
  47.   
  48.         public Builder addTatble(Class<? extends BaseBean<?>> table) {  
  49.             tableList.add(table);  
  50.             return this;  
  51.         }  
  52.           
  53.         public Builder setAuthority(String authority){  
  54.             this.authority = authority;  
  55.             return this;  
  56.         }  
  57.           
  58.         public DBConfig build(){  
  59.             return new DBConfig(this);  
  60.         }  
  61.     }  
  62.   
  63. }  

通过该类,来设置数据库的参数,在初始化数据库的时候用到。

内容提供者类,初始化和操作数据库

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public abstract class IssContentProvider extends ContentProvider {  
  2.     public static String CONTENT_TYPE = "vnd.android.cursor.dir/iss.db";  
  3.   
  4.     protected SQLiteDatabase mDB;  
  5.   
  6.     public static String AUTHORITY = "com.iss.mobile";  
  7.   
  8.     @Override  
  9.     public boolean onCreate() {  
  10.          init();  
  11.         IssDBFactory issDBFactory = IssDBFactory.getInstance();  
  12.         DBConfig config = IssDBFactory.getInstance().getDBConfig();  
  13.         if (config == null) {  
  14.             throw new RuntimeException("db factory not init");  
  15.         }  
  16.         AUTHORITY = config.authority;  
  17.         CONTENT_TYPE = "vnd.android.cursor.dir/" + config.dbName;  
  18.         mDB = issDBFactory.open();  
  19.         return true;  
  20.     }  
  21.   
  22.     public abstract void init();  
  23.   
  24.     public static final String SCHEME = "content";  
  25.   
  26.     @Override  
  27.     public Uri insert(Uri uri, ContentValues values) {  
  28.         String tableName = getTableName(uri);  
  29.         long result = mDB.insert(tableName, null, values);  
  30.         if (result != -1) {  
  31.             getContext().getContentResolver().notifyChange(uri, null);  
  32.         }  
  33.         return buildResultUri(tableName, result);  
  34.     }  
  35.       
  36.     @Override  
  37.     public int bulkInsert(Uri uri, ContentValues[] values) {  
  38.         mDB.beginTransaction();  
  39.         String tableName = getTableName(uri);  
  40.         for(ContentValues value:values){  
  41.             mDB.insert(tableName, null, value);  
  42.         }  
  43.         mDB.setTransactionSuccessful();  
  44.         mDB.endTransaction();  
  45.         return values.length;  
  46.     }  
  47.   
  48.     @Override  
  49.     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,  
  50.             String sortOrder) {  
  51.         String tableName = getTableName(uri);  
  52.         return mDB.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);  
  53.     }  
  54.   
  55.     @Override  
  56.     public String getType(Uri uri) {  
  57.         return CONTENT_TYPE;  
  58.     }  
  59.   
  60.     @Override  
  61.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  62.         String tableName = getTableName(uri);  
  63.         int result = mDB.delete(tableName, selection, selectionArgs);  
  64.         if (result != 0) {  
  65.             getContext().getContentResolver().notifyChange(uri, null);  
  66.         }  
  67.         return result;  
  68.     }  
  69.   
  70.     @Override  
  71.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {  
  72.         String tableName = getTableName(uri);  
  73.         int result = mDB.update(tableName, values, selection, selectionArgs);  
  74.         if (result != 0) {  
  75.             getContext().getContentResolver().notifyChange(uri, null);  
  76.         }  
  77.         return result;  
  78.     }  
  79.   
  80.     private Uri buildResultUri(String tableName, long result) {  
  81.         final Uri.Builder builder = new Uri.Builder();  
  82.         DBConfig config = IssDBFactory.getInstance().getDBConfig();  
  83.         if (config == null) {  
  84.             throw new RuntimeException("db factory not init");  
  85.         }  
  86.         builder.scheme(SCHEME);  
  87.         builder.authority(config.authority);  
  88.         builder.path(tableName);  
  89.         builder.appendPath(String.valueOf(result));  
  90.         return builder.build();  
  91.     }  
  92.   
  93.     private String getTableName(Uri uri) {  
  94.         DBConfig config = IssDBFactory.getInstance().getDBConfig();  
  95.         if (config == null) {  
  96.             throw new RuntimeException("db factory not init");  
  97.         }  
  98.         String path = uri.getLastPathSegment();  
  99.         if (!config.tableNameList.contains(path)) {  
  100.             throw new IllegalArgumentException("Unknown URI " + uri);  
  101.         }  
  102.         return path;  
  103.     }  
  104.   
  105.     public static Uri buildUri(String path, String id) {  
  106.         final Uri.Builder builder = new Uri.Builder();  
  107.         DBConfig config = IssDBFactory.getInstance().getDBConfig();  
  108.         if (config == null) {  
  109.             throw new RuntimeException("db factory not init");  
  110.         }  
  111.         builder.scheme(SCHEME);  
  112.         builder.authority(config.authority);  
  113.         builder.path(path);  
  114.         builder.appendPath(id);  
  115.         return builder.build();  
  116.     }  
  117.   
  118.     public static Uri buildUri(String path) {  
  119.         final Uri.Builder builder = new Uri.Builder();  
  120.         DBConfig config = IssDBFactory.getInstance().getDBConfig();  
  121.         if (config == null) {  
  122.             throw new RuntimeException("db factory not init");  
  123.         }  
  124.         builder.scheme(SCHEME);  
  125.         builder.authority(config.authority);  
  126.         builder.path(path);  
  127.         return builder.build();  
  128.     }  
  129.   
  130.     public static Uri buildUri(Class<? extends BaseBean<?>> c) {  
  131.         final String tableName = TableUtil.getTableName(c);  
  132.         return buildUri(tableName);  
  133.     }  
  134.   
  135. }  

该内容提供者在创建的时候,先执行init()(将要数据库的参数设置好,再将参数传递给工厂类),工厂类根据参数创建数据库mDB = issDBFactory.open();
数据库工厂类:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class IssDBFactory {  
  2.     private static final String TAG = IssDBFactory.class.getSimpleName();  
  3.   
  4.     private DBConfig mConfig;  
  5.     private SQLiteDatabase mSQLiteDB;  
  6.   
  7.     private IssDBOpenHelper mDBOpenHelper;  
  8.   
  9.     private final Context mContext;  
  10.       
  11.     private static IssDBFactory instance ;  
  12.   
  13.     private IssDBFactory(Context context) {  
  14.         mContext = context;  
  15.     }  
  16.       
  17.     public static void init(Context context,DBConfig dbConfig){  
  18.         if(instance==null){  
  19.             instance = new IssDBFactory(context.getApplicationContext());  
  20.             instance.setDBConfig(dbConfig);  
  21.         }  
  22.     }  
  23.       
  24.     public static IssDBFactory getInstance(){  
  25.         return instance;  
  26.     }  
  27.       
  28.       
  29.     public void setDBConfig(DBConfig dbConfig){  
  30.         mConfig = dbConfig;  
  31.     }  
  32.       
  33.     public DBConfig getDBConfig(){  
  34.         return mConfig;  
  35.     }  
  36.   
  37.     public SQLiteDatabase open() {  
  38.         if(mSQLiteDB==null){  
  39.             mDBOpenHelper = new IssDBOpenHelper(mContext, mConfig.dbName, null, mConfig.dbVersion);  
  40.             mSQLiteDB = mDBOpenHelper.getWritableDatabase();  
  41.         }  
  42.         return mSQLiteDB;  
  43.     }  
  44.   
  45.     public void close() {  
  46.         if(mDBOpenHelper!=null){  
  47.             mDBOpenHelper.close();  
  48.         }  
  49.     }  
  50.   
  51.     public void beginTransaction() {  
  52.         if(mSQLiteDB==null){  
  53.             mSQLiteDB.beginTransaction();  
  54.         }  
  55.     }  
  56.   
  57.     public void endTransaction() {  
  58.         if (mSQLiteDB==null&&mSQLiteDB.inTransaction()) {  
  59.             mSQLiteDB.endTransaction();  
  60.         }  
  61.     }  
  62.   
  63.     public void setTransactionSuccessful() {  
  64.         if (mSQLiteDB==null){  
  65.             mSQLiteDB.setTransactionSuccessful();  
  66.         }  
  67.     }  
  68.   
  69.     private final class IssDBOpenHelper extends SQLiteOpenHelper {  
  70.   
  71.         public IssDBOpenHelper(Context context, String name, CursorFactory factory, int version) {  
  72.             super(context, name, factory, version);  
  73.         }  
  74.   
  75.         @Override  
  76.         public void onCreate(SQLiteDatabase db) {  
  77.             for (Class<? extends BaseBean<?>> table : mConfig.tableList) {  
  78.                 try {  
  79.                     for (String statment : TableUtil.getCreateStatments(table)) {  
  80.                         Log.d(TAG, statment);  
  81.                         db.execSQL(statment);  
  82.                     }  
  83.                 } catch (Throwable e) {  
  84.                     Log.e(TAG, "Can't create table " + table.getSimpleName());  
  85.                 }  
  86.             }  
  87.   
  88.             /** 
  89.              * 初始化数据 
  90.              */  
  91.             // initData();  
  92.   
  93.         }  
  94.   
  95.         @Override  
  96.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  97.             Log.d(TAG, "onUpgrade: " + oldVersion + " >> " + newVersion);  
  98.             for (Class<? extends BaseBean<?>> table : mConfig.tableList) {  
  99.                 try {  
  100.                     db.execSQL("DROP TABLE IF EXISTS " + TableUtil.getTableName(table));  
  101.                 } catch (Throwable e) {  
  102.                     Log.e(TAG, "Can't create table " + table.getSimpleName());  
  103.                 }  
  104.             }  
  105.             onCreate(db);  
  106.         }  
  107.   
  108.     }  
  109.   
  110.     public void cleanTable(String tableName, int maxSize, int batchSize) {  
  111.         Cursor cursor = mSQLiteDB.rawQuery("select count(_id) from " + tableName, null);  
  112.         if (cursor.getCount() != 0 && cursor.moveToFirst() && !cursor.isAfterLast()) {  
  113.             if (cursor.getInt(0) >= maxSize) {  
  114.                 int deleteSize = maxSize - batchSize;  
  115.                 mSQLiteDB.execSQL("delete from " + tableName + " where _id in (" + "select _id from " + tableName  
  116.                         + " order by _id " + "  limit " + deleteSize + " )");  
  117.             }  
  118.         }  
  119.         cursor.close();  
  120.     }  

 

看到这用过数据库的就比较清晰了,用到了SQLiteOpenHelper是以内部类的形式实现的,在oncreat里创建了表,在onupgrade里实现了更新表。

其中用到TableUtil.getCreateStatments(table),

数据库工具类:

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. public class TableUtil {  
  2.   
  3.     public static String getTableName(Class<? extends BaseBean<?>> c) {  
  4.         String name = null;  
  5.         Table tableNameAnnotation = c.getAnnotation(Table.class);  
  6.         if (tableNameAnnotation != null) {  
  7.             name = tableNameAnnotation.name();  
  8.         }  
  9.         if (TextUtils.isEmpty(name)) {  
  10.             name = c.getSimpleName();  
  11.         }  
  12.         return name;  
  13.     }  
  14.   
  15.     /** 
  16.      * 拼装sql用的建表语句以及索引语句 
  17.      *  
  18.      * @param c 
  19.      * @return 
  20.      */  
  21.     public final static List<String> getCreateStatments(Class<? extends BaseBean<?>> c) {  
  22.         final List<String> createStatments = new ArrayList<String>();  
  23.         final List<String> indexStatments = new ArrayList<String>();  
  24.   
  25.         final StringBuilder builder = new StringBuilder();  
  26.         final String tableName = getTableName(c);  
  27.         builder.append("CREATE TABLE ");  
  28.         builder.append(tableName);  
  29.         builder.append(" (");  
  30.         int columnNum = 0;  
  31.         for (final Field f : c.getFields()) {  
  32.             f.setAccessible(true);  
  33.             final TableColumn tableColumnAnnotation = f.getAnnotation(TableColumn.class);  
  34.             if (tableColumnAnnotation != null) {  
  35.                 columnNum++;  
  36.                 String columnName = f.getName();  
  37.                 builder.append(columnName);  
  38.                 builder.append(" ");  
  39.                 if (tableColumnAnnotation.type() == TableColumn.Types.INTEGER) {  
  40.                     builder.append(" INTEGER");  
  41.                 } else if (tableColumnAnnotation.type() == TableColumn.Types.BLOB) {  
  42.                     builder.append(" BLOB");  
  43.                 } else if (tableColumnAnnotation.type() == TableColumn.Types.TEXT) {  
  44.                     builder.append(" TEXT");  
  45.                 } else {  
  46.                     builder.append(" DATETIME");  
  47.                 }  
  48.                 if (tableColumnAnnotation.isPrimary()) {  
  49.                     builder.append(" PRIMARY KEY");  
  50.                 } else {  
  51.                     if (tableColumnAnnotation.isNotNull()) {  
  52.                         builder.append(" NOT NULL");  
  53.                     }  
  54.                     if (tableColumnAnnotation.isUnique()) {  
  55.                         builder.append(" UNIQUE");  
  56.                     }  
  57.                 }  
  58.                 if (tableColumnAnnotation.isIndex()) {  
  59.                     indexStatments.add("CREATE INDEX idx_" + columnName + "_" + tableName + " ON "  
  60.                             + tableName + "(" + columnName + ");");  
  61.                 }  
  62.                 builder.append(", ");  
  63.             }  
  64.         }  
  65.         builder.setLength(builder.length() - 2); // remove last ','  
  66.         builder.append(");");  
  67.         if (columnNum > 0) {  
  68.             createStatments.add(builder.toString());  
  69.             createStatments.addAll(indexStatments);  
  70.         }  
  71.         return createStatments;  
  72.     }  
  73.   
  74. }  

就两个方法,获取表名,在更新表的时候用到,拼装sql在创建表时候用到。
最后两个标签类:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. @Retention(RetentionPolicy.RUNTIME)  
  2. public @interface Table {  
  3.     String name();  
  4. }  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. @Retention(RetentionPolicy.RUNTIME)  
  2. public @interface TableColumn {  
  3.     public enum Types {  
  4.         INTEGER, TEXT, BLOB, DATETIME  
  5.     }  
  6.   
  7.     Types type() default Types.TEXT;  
  8.   
  9.     boolean isPrimary() default false;  
  10.   
  11.     boolean isIndex() default false;  
  12.   
  13.     boolean isNotNull() default false;  
  14.   
  15.        boolean isUnique() default false;  
  16.       
  17. }  

思路比较简单,就是注意先标签、过滤器、内容提供者的使用就行了。

最后是封装包代码,使用过程没有加,自己加入吧:http://download.csdn.net/detail/xiangxue336/7001299

posted @ 2015-01-05 10:09  dongweiq  阅读(2074)  评论(0编辑  收藏  举报