[置顶] 关于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);
        }
    }
 
 


 

你可能感兴趣的:(android)