android資料庫操作封裝

來源:互聯網
上載者:User

EntityDao.java代碼如下:

import java.io.Serializable;import java.util.List;/** * 基本DAO介面 * @author EwinLive * * @param <T> * @param <PK> */public interface EntityDao<T, PK extends Serializable> {/** * 添加 * @param entity */void save(final T entity) throws Exception;/** * 移除記錄(指定ID集) * @param ids 可以有多個 */void remove(final PK... ids);/** * 更新 * @param entity * @throws Exception  */void upDate(final T entity) throws Exception;/** * 按ID查詢對象 * @param id * @return */T find(final PK id);/** * 分頁查詢 * @param startResult 開始位置 * @param maxResult 記錄容量 * @return * @throws Exception  */List<T> getScroolData(Integer startResult, Integer maxResult);/** * 返回記錄總數 * @return */public Long getCount();}

SimpleDao.java代碼如下:

import java.io.Serializable;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import org.dw.core.utils.BeanTools;import org.dw.ivb.utils.DataBaseHelper;import android.content.Context;import android.database.Cursor;/** * 實現了EntityDao介面,其他實體DAO只要繼承它即可擁有所有強大功能。 * @author EwinLive * * @param <T> * @param <PK> */public abstract class SimpleDao<T, PK extends Serializable> implements EntityDao<T, PK> {/** * 實體的類型 */protected Class<T> entityClass;/** * 表名 */protected String tableName;/** * 資料庫管理員 */protected DataBaseHelper dbHelper;/** * 儲存實體所要執行的SQL語句 * 只在建立對象時初始化。 */protected String saveSql;/** * 更新實體所要執行的SQL語句 * 只在建立對象時初始化。 */protected String updateSql;/** * 欄位在資料表中所對應的列的索引 * 只在建立對象時初始化。 */protected int[] fieldPostion;public String getTableName() {return tableName;}public void setTableName(String tableName) {this.tableName = tableName;}public DataBaseHelper getDbHelper() {return dbHelper;}public void setDbHelper(DataBaseHelper dbHelper) {this.dbHelper = dbHelper;}public String getSaveSql() {return saveSql;}public void setSaveSql(String saveSql) {this.saveSql = saveSql;}public String getUpdateSql() {return updateSql;}public void setUpdateSql(String updateSql) {this.updateSql = updateSql;}/** * 專屬構造器 * 可通過子類的範型定義取得物件類型Class. * @param tableName 實體對應的表名 * @param context 裝置上下文,通常是一個Activity對象 */@SuppressWarnings("unchecked")public SimpleDao(String tableName, Context context) {this.entityClass = (Class<T>) BeanTools.getGenericClass(getClass());this.tableName = tableName;this.dbHelper = new DataBaseHelper(context);this.saveSql = initSaveSql();this.updateSql = initUpdateSql();this.fieldPostion = initFieldPostion();}@Overridepublic void save(T entity) throws Exception {dbHelper.getReadableDatabase().execSQL(saveSql, getSaveValue(entity));}@SuppressWarnings("unused")@Overridepublic void remove(PK... ids) {if(ids.length > 0){StringBuffer sb = new StringBuffer();for(PK id : ids){sb.append('?').append(',');}sb.deleteCharAt(sb.length() - 1);dbHelper.getReadableDatabase().execSQL("delete from "+ tableName +" where id in(" + sb + ")", (Object[]) ids);}}@Overridepublic void upDate(T entity) throws Exception {dbHelper.getReadableDatabase().execSQL(updateSql, getUpdateValue(entity));}@Overridepublic T find(PK id) {Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " where id=?", new String[]{String.valueOf(id)});cursor.moveToNext();return getEntityFromCursor(cursor);}@Overridepublic List<T> getScroolData(Integer startResult, Integer maxResult){List<T> list = new ArrayList<T>(0);Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?", new String[]{String.valueOf(startResult), String.valueOf(maxResult)});while(cursor.moveToNext()){list.add(getEntityFromCursor(cursor));}return list;}@Overridepublic Long getCount() {Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select count(*) from " + tableName, null);if(cursor.moveToNext())return cursor.getLong(0);return 0l;}/** * 初始化儲存實體所需的SQL語句 * @return */@SuppressWarnings("rawtypes")protected String initSaveSql(){HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");StringBuffer bufferName = new StringBuffer();StringBuffer bufferExpr = new StringBuffer();for(String tmp : fieldName){bufferName.append(tmp).append(',');bufferExpr.append("?,");}//去除id欄位及其屬性值bufferName.delete(bufferName.indexOf("id"), bufferName.indexOf("id")+3);bufferExpr.delete(0, 2);//去除多餘的分隔字元bufferName.deleteCharAt(bufferName.length()-1);bufferExpr.deleteCharAt(bufferExpr.length()-1);String sql = "insert into "+ tableName+ "(" + bufferName.toString() + ") values(" + bufferExpr.toString() + ")";return sql;}/** * 初始化更新實體所需的SQL語句 * @return */@SuppressWarnings("rawtypes")protected String initUpdateSql(){HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");StringBuffer sqlBuffer = new StringBuffer();sqlBuffer.append("update "+ tableName + " set ");for(String tmp : fieldName){sqlBuffer.append(tmp).append("=?, ");}//去除id欄位及其屬性值sqlBuffer.delete(sqlBuffer.indexOf(" id=?"), sqlBuffer.indexOf("id") + 5);sqlBuffer.deleteCharAt(sqlBuffer.length()-2);sqlBuffer.append("where id =?");return sqlBuffer.toString();}/** * 擷取儲存實體所需的值 * @param entity * @return * @throws IllegalAccessException * @throws NoSuchFieldException */@SuppressWarnings("rawtypes")protected Object[] getSaveValue(T entity) throws IllegalAccessException, NoSuchFieldException{HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");Object[] values;int length = fieldName.length;values = new Object[length-1];int j=0;for(int i=0; i<length; i++){if("id".equals(fieldName[i].toString())){continue;//跳過ID欄位}values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]);}return values;}/** * 擷取更新實體所需的值 * @param entity * @return * @throws IllegalAccessException * @throws NoSuchFieldException */@SuppressWarnings("rawtypes")protected Object[] getUpdateValue(T entity) throws Exception{HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");Object[] values;int length = fieldName.length;values = new Object[length-1];int j=0;int id=0;for(int i=0; i<length; i++){if("id".equals(fieldName[i].toString())){id = (Integer) BeanTools.getPrivateProperty(entity, fieldName[i]);continue;//跳過ID欄位}values[j++] = BeanTools.getPrivateProperty(entity, fieldName[i]);}Object[] values2 = new Object[length];System.arraycopy(values, 0, values2, 0, values.length);values2[length-1] = id;return values2;}/** * 初始化欄位在資料表中 對應的索引 * @param cursor */@SuppressWarnings("rawtypes")protected int[] initFieldPostion(){HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");int length = fieldName.length;int[] postion = new int[length];Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from " + tableName + " limit ?, ?", new String[]{"0", "2"});for(int i =0; i<length; i++){postion[i] = cursor.getColumnIndex(fieldName[i]);}return postion;}/** * 從遊標中擷取實體 * @param cursor 遊標 * @return T 實體物件 */@SuppressWarnings("rawtypes")public T getEntityFromCursor(Cursor cursor){HashMap data = BeanTools.getAllFiled(entityClass);String[] fieldName = (String[]) data.get("fieldName");Class<?>[] fieldType = (Class<?>[]) data.get("fieldType");int length = fieldName.length;T entity = null;String db_data;String fieldTypeName;try {entity = entityClass.newInstance();for(int i=0;i<length;i++){fieldTypeName = fieldType[i].getSimpleName();db_data = cursor.getString(fieldPostion[i]);if(null != db_data){if("String".equals(fieldTypeName)){BeanTools.setFieldValue(entity, fieldName[i], db_data);}else if("int".equals(fieldTypeName)){BeanTools.setFieldValue(entity, fieldName[i], Integer.parseInt(db_data));}else if("long".equals(fieldTypeName)){BeanTools.setFieldValue(entity, fieldName[i], Long.getLong(db_data));}else if("float".equals(fieldTypeName)){BeanTools.setFieldValue(entity, fieldName[i],Float.parseFloat(db_data));}}}} catch (Exception e) {System.out.println(e.getMessage());}return entity;}}

BeanTools.java代碼如下:

package org.dw.core.utils;import java.lang.reflect.Field;import java.lang.reflect.Modifier;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.HashMap;import org.apache.commons.beanutils.ConvertUtils;/** * Bean工具類 * @author EwinLive * */public abstract class BeanTools {/** * 擷取第一個泛型類 */public static Class<?> getGenericClass(Class<?> clazz) {return getGenericClass(clazz, 0);}/** * 擷取泛型類 */public static Class<?> getGenericClass(Class<?> clazz, int index) throws IndexOutOfBoundsException {Type genType = clazz.getGenericSuperclass();if (!(genType instanceof ParameterizedType)) {return Object.class;}Type[] params = ((ParameterizedType) genType).getActualTypeArguments();if (index >= params.length || index < 0) {throw new IndexOutOfBoundsException("Index: " + index + ", Size of Parameterized Type: " + params.length);}return (Class<?>) params[index];}/** * 直接設定對象屬性值, 無視private/protected修飾符, 不經過setter函數. */public static void setFieldValue(final Object object, final String fieldName, final Object value) {Field field = getDeclaredField(object, fieldName);if (field == null) {throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");}makeAccessible(field);try {field.set(object, value);} catch (IllegalAccessException e) {//logger.error("不可能拋出的異常:{}", e.getMessage());}}/** * 強行設定Field可訪問. */protected static void makeAccessible(final Field field) {if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {field.setAccessible(true);}}/** * 迴圈向上轉型, 擷取對象的DeclaredField. *  * 如向上轉型到Object仍無法找到, 返回null. */protected static Field getDeclaredField(final Object object, final String fieldName) {//Assert.notNull(object, "object不可為空");//Assert.hasText(fieldName, "fieldName");for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {try {return superClass.getDeclaredField(fieldName);} catch (NoSuchFieldException e) {// Field不在當前類定義,繼續向上轉型}}return null;}/** * 轉換字串到相應類型. *  * @param value 待轉換的字串 * @param toType 轉換目標類型 */public static Object convertStringToObject(String value, Class<?> toType) {if (StringTools.isNotEmpty(value)) {return ConvertUtils.convert(value, toType);} else {return null;}}/** * 強行擷取私人屬性的值 */public static Object getPrivateProperty(Object object, String propertyName) throws IllegalAccessException, NoSuchFieldException {//Assert.notNull(object);//Assert.hasText(propertyName);Field field = object.getClass().getDeclaredField(propertyName);field.setAccessible(true);return field.get(object);}/** * 強行設定私人屬性的值 */public static void setPrivateProperty(Object object, String propertyName, Object newValue) throws IllegalAccessException, NoSuchFieldException {//Assert.notNull(object);//Assert.hasText(propertyName);Field field = object.getClass().getDeclaredField(propertyName);field.setAccessible(true);field.set(object, newValue);}/** * 擷取所有欄位 * @param entityClass 實體的類型 * @return data  * 返回包含兩個數組的HashMap,可參考以下使用方法: * String[] fieldName = (String[]) data.get("fieldName"); * Class<?>[] fieldType = (Class<?>[]) data.get("fieldType"); */public static HashMap<Object, Object> getAllFiled(Class<?> entityClass){HashMap<Object, Object> data = new HashMap<Object, Object>();Field[]  fields = entityClass.getDeclaredFields();String[] fieldName = new String[fields.length];Class<?>[] fieldType = new Class<?>[fields.length];for(int i=0; i<fields.length; i++){fieldName[i] = fields[i].getName();//組裝名稱數組fieldType[i] = fields[i].getType();//組裝類型數組}data.put("fieldName", fieldName);data.put("fieldType", fieldType);return data;}}

還有其他很多代碼:已經上傳了!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.