1. 程式人生 > >關於ormlite-android用法詳解

關於ormlite-android用法詳解

首先說明一下,本人已經使用ormlite-android做過兩個大型的專案開發,很久以來就想對此資料庫做一些總結,正好今天有空就寫出來:

1. 首先去官網http://ormlite.com/看官方說明,也可以去http://ormlite.com/releases/下載兩個包:一個是ormlite-core-4.24.jar,另一個是ormlite-android-4.24.jar

2. 下載完2個jar包後匯入專案中,在此不多說,大家都懂的

3.前奏工作完成,下面就是怎麼去搭建框架使用了,首先說明本人做過一段時間的web開發,所以喜歡用mvc模式,下面將通過程式碼來說明:

   1).建立自己的DatabaseHelper類

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    // name of the database file for your application -- change to something
    // appropriate for your app
    private static final String DATABASE_NAME = "CHENGYIJI.db";

    // any time you make changes to your database objects, you may have to
    // increase the database version
    private static final int DATABASE_VERSION = 1;

    // the DAO object we use to access the SimpleData table

    //資料庫預設路徑SDCard
    private static String DATABASE_PATH = Environment.getExternalStorageDirectory()
            + "/CHENGYIJI.db";

    private Context mContext;

    //資料庫配置檔案預設路徑SDCard
    private static String DATABASE_PATH_JOURN = Environment.getExternalStorageDirectory()
            + "/CHEYIJI.db-journal";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
        initDtaBasePath();
        try {

            File f = new File(DATABASE_PATH);
            if (!f.exists()) {
                SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH, null);
                onCreate(db);
                db.close();
            }
        } catch (Exception e) {
        }
    }

     //如果沒有SDCard 預設儲存在專案檔案目錄下
    private void initDtaBasePath() {
        if (!Utils.ExistSDCard()) {
            DATABASE_PATH = mContext.getFilesDir().getAbsolutePath() + "/CHENGYIJI.db";
            DATABASE_PATH_JOURN = mContext.getFilesDir().getAbsolutePath() + "/CHEYIJI.db-journal";
        }
    }

    @Override
    public synchronized SQLiteDatabase getWritableDatabase() {
        return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    }

    public synchronized SQLiteDatabase getReadableDatabase() {
        return SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READONLY);
    }

    /**
     * This is called when the database is first created. Usually you should
     * call createTable statements here to create the tables that will store
     * your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        LogTool.i(DatabaseHelper.class.getName(), "onCreate");
        try {
            TableUtils.createTable(connectionSource, UserInfo.class);
        } catch (java.sql.SQLException e) {
            LogTool.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }

    }

    /**
     * This is called when your application is upgraded and it has a higher
     * version number. This allows you to adjust the various data to match the
     * new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion,
            int newVersion) {
        LogTool.i(DatabaseHelper.class.getName(), "onUpgrade");
        try {
            TableUtils.dropTable(connectionSource, UserInfo.class, true);
            onCreate(db, connectionSource);
        } catch (java.sql.SQLException e) {
            LogTool.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }


    public void deleteDB() {
        if (mContext != null) {
            File f = mContext.getDatabasePath(DATABASE_NAME);
            if (f.exists()) {
                // mContext.deleteDatabase(DATABASE_NAME);
                LogTool.e("DB", "---delete SDCard DB---");
                f.delete();
            } else {
                LogTool.e("DB", "---delete App DB---");
                mContext.deleteDatabase(DATABASE_NAME);
            }

            File file = mContext.getDatabasePath(DATABASE_PATH);
            if (file.exists()) {
                LogTool.e("DB", "---delete SDCard DB 222---");
                file.delete();
            }

            File file2 = mContext.getDatabasePath(DATABASE_PATH_JOURN);
            if (file2.exists()) {
                LogTool.e("DB", "---delete SDCard DB 333---");
                file2.delete();
            }
        }
    }

    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
    }
}
2)建立自己的資料庫操作Dao層】
public abstract class BaseDao<T, Integer> {
    protected DatabaseHelper mDatabaseHelper;

    protected Context mContext;

    public BaseDao(Context context) {
        mContext = context;
        getHelper();
    }

    public DatabaseHelper getHelper() {
        if (mDatabaseHelper == null) {
            mDatabaseHelper = OpenHelperManager.getHelper(mContext, DatabaseHelper.class);
        }
        return mDatabaseHelper;
    }

    public abstract Dao<T, Integer> getDao() throws SQLException;

    public int save(T t) throws SQLException {
        return getDao().create(t);
    }

    public List<T> query(PreparedQuery<T> preparedQuery) throws SQLException {
        Dao<T, Integer> dao = getDao();
        return dao.query(preparedQuery);
    }

    public List<T> query(String attributeName, String attributeValue) throws SQLException {
        QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
        queryBuilder.where().eq(attributeName, attributeValue);
        PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        return query(preparedQuery);
    }

    public List<T> query(String[] attributeNames, String[] attributeValues) throws SQLException,
            InvalidParamsException {
        if (attributeNames.length != attributeValues.length) {
            throw new InvalidParamsException("params size is not equal");
        }
        QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
        Where<T, Integer> wheres = queryBuilder.where();
        for (int i = 0; i < attributeNames.length; i++) {
            wheres.eq(attributeNames[i], attributeValues[i]);
        }
        PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        return query(preparedQuery);
    }

    public List<T> queryAll() throws SQLException {
        // QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
        // PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        // return query(preparedQuery);
        Dao<T, Integer> dao = getDao();
        return dao.queryForAll();
    }

    public T queryById(String idName, String idValue) throws SQLException {
        List<T> lst = query(idName, idValue);
        if (null != lst && !lst.isEmpty()) {
            return lst.get(0);
        } else {
            return null;
        }
    }

    public int delete(PreparedDelete<T> preparedDelete) throws SQLException {
        Dao<T, Integer> dao = getDao();
        return dao.delete(preparedDelete);
    }

    public int delete(T t) throws SQLException {
        Dao<T, Integer> dao = getDao();
        return dao.delete(t);
    }

    public int delete(List<T> lst) throws SQLException {
        Dao<T, Integer> dao = getDao();
        return dao.delete(lst);
    }

    public int delete(String[] attributeNames, String[] attributeValues) throws SQLException,
            InvalidParamsException {
        List<T> lst = query(attributeNames, attributeValues);
        if (null != lst && !lst.isEmpty()) {
            return delete(lst);
        }
        return 0;
    }

    public int deleteById(String idName, String idValue) throws SQLException,
            InvalidParamsException {
        T t = queryById(idName, idValue);
        if (null != t) {
            return delete(t);
        }
        return 0;
    }

    public int update(T t) throws SQLException {
        Dao<T, Integer> dao = getDao();
        return dao.update(t);
    }

    public boolean isTableExsits() throws SQLException {
        return getDao().isTableExists();
    }

    public long countOf() throws SQLException {
        return getDao().countOf();
    }

    public List<T> query(Map<String, Object> map) throws SQLException {
        QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
        if (!map.isEmpty()) {
            Where<T, Integer> wheres = queryBuilder.where();
            Set<String> keys = map.keySet();
            ArrayList<String> keyss = new ArrayList<String>();
            keyss.addAll(keys);
            for (int i = 0; i < keyss.size(); i++) {
                if (i == 0) {
                    wheres.eq(keyss.get(i), map.get(keyss.get(i)));
                } else {
                    wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));
                }
            }
        }
        PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        return query(preparedQuery);
    }

    public List<T> query(Map<String, Object> map, Map<String, Object> lowMap,
            Map<String, Object> highMap) throws SQLException {
        QueryBuilder<T, Integer> queryBuilder = getDao().queryBuilder();
        Where<T, Integer> wheres = queryBuilder.where();
        if (!map.isEmpty()) {
            Set<String> keys = map.keySet();
            ArrayList<String> keyss = new ArrayList<String>();
            keyss.addAll(keys);
            for (int i = 0; i < keyss.size(); i++) {
                if (i == 0) {
                    wheres.eq(keyss.get(i), map.get(keyss.get(i)));
                } else {
                    wheres.and().eq(keyss.get(i), map.get(keyss.get(i)));
                }
            }
        }
        if (!lowMap.isEmpty()) {
            Set<String> keys = lowMap.keySet();
            ArrayList<String> keyss = new ArrayList<String>();
            keyss.addAll(keys);
            for (int i = 0; i < keyss.size(); i++) {
                if(map.isEmpty()){
                    wheres.gt(keyss.get(i), lowMap.get(keyss.get(i)));
                }else{
                    wheres.and().gt(keyss.get(i), lowMap.get(keyss.get(i)));
                }
            }
        }

        if (!highMap.isEmpty()) {
            Set<String> keys = highMap.keySet();
            ArrayList<String> keyss = new ArrayList<String>();
            keyss.addAll(keys);
            for (int i = 0; i < keyss.size(); i++) {
                wheres.and().lt(keyss.get(i), highMap.get(keyss.get(i)));
            }
        }
        PreparedQuery<T> preparedQuery = queryBuilder.prepare();
        return query(preparedQuery);
    }
}

3)怎麼應用
首先有一個model物件

public class CashFlow implements ICashFlowRecorder, Serializable {     /**      *      */     private static final long serialVersionUID = 1L;

    // 流水號ID     @DatabaseField(generatedId = true, columnName = "cash_flow_id")     private long cashFlowId;

    // 型別:0收,1支     @DatabaseField(canBeNull = false, columnName = "type")     private int type;

    // 資金型別 - 0 貸款,1借款,2貨款,3其他     @DatabaseField(canBeNull = false, columnName = "cash_type")     private int cashType;

    // 資金型別為其他是的 描述     @DatabaseField(columnName = "other_type_desc")     private String otherTypeDesc;

    // 是否參與核銷:0否,1是     @DatabaseField(canBeNull = false, columnName = "write_off_flag")     private int writeOffFlag;

    // 關聯使用者ID     // private long referUserId;     @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "phone_book_id")     private PhoneBook referUser;

    // 資金     @DatabaseField(canBeNull = false, columnName = "amount")     private double amount;

    // 登記日期     @DatabaseField(canBeNull = false, columnName = "reg_date")     private long regDate;

    // 建立時間     @DatabaseField(canBeNull = false, columnName = "create_date")     private long createDate;

    // 修改時間     @DatabaseField(canBeNull = false, columnName = "update_date")     private long updateDate;

    // 關聯賬單ID     @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "bill_id")     private Bill referBill;

    public long getCashFlowId() {         return cashFlowId;     }

    public void setCashFlowId(long cashFlowId) {         this.cashFlowId = cashFlowId;     }

    public int getType() {         return type;     }

    public void setType(int type) {         this.type = type;     }

    public int getCashType() {         return cashType;     }

    public void setCashType(int cashType) {         this.cashType = cashType;     }

    public String getOtherTypeDesc() {         return otherTypeDesc;     }

    public void setOtherTypeDesc(String otherTypeDesc) {         this.otherTypeDesc = otherTypeDesc;     }

    public int getWriteOffFlag() {         return writeOffFlag;     }

    public void setWriteOffFlag(int writeOffFlag) {         this.writeOffFlag = writeOffFlag;     }

    public PhoneBook getReferUser() {         return referUser;     }

    public void setReferUser(PhoneBook referUser) {         this.referUser = referUser;     }

    public double getAmount() {         return amount;     }

    public void setAmount(double amount) {         this.amount = amount;     }

    public long getRegDate() {         return regDate;     }

    public void setRegDate(long regDate) {         this.regDate = regDate;     }

    public long getCreateDate() {         return createDate;     }

    public void setCreateDate(long createDate) {         this.createDate = createDate;     }

    public long getUpdateDate() {         return updateDate;     }

    public void setUpdateDate(long updateDate) {         this.updateDate = updateDate;     }

    public Bill getReferBill() {         return referBill;     }

    public void setReferBill(Bill referBill) {         this.referBill = referBill;     }

}

然後建立自己的dao

public class CashFlowDao extends BaseDao<CashFlow, Integer> {

 public CashFlowDao(Context context) {   super(context);  }

 @Override  public Dao<CashFlow, Integer> getDao() throws SQLException {   return getHelper().getDao(CashFlow.class);  }

}

最後應用dao,查詢某一段時間內的CashFlow
 @SuppressWarnings("deprecation")
    private void queCashFlow(int msgType, long lowTime, long highTime) {
        try {
            CashFlowDao cashFlowDao = new CashFlowDao(this);
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> lowMap = new HashMap<String, Object>();
            lowMap.put("create_date", lowTime);
            Map<String, Object> highMap = new HashMap<String, Object>();
            highMap.put("create_date", highTime);
            ArrayList<CashFlow> cashFlows = (ArrayList<CashFlow>)cashFlowDao.query(map, lowMap,
                    highMap);
            if (cashFlows != null && cashFlows.size() > 0) {
                Message message = new Message();
                message.what = msgType;
                message.obj = cashFlows;
                handler.sendMessage(message);
            } else {
                handler.sendEmptyMessage(4);
            }
        } catch (SQLException e) {
            handler.sendEmptyMessage(4);
        }
    }