標籤:
OrmLite是一個輕量級的對象關係映射包,由Java語言開發。Github上有ormlite-core,ormlite-android,ormlite-examples,分別是主要庫,android依賴和一些教程。
一、準備
為了在android上使用OrmLite,我們需要下載ormlite-core.jar和ormlite-android.jar放到項目目錄下,然後:
1、建立一個類繼承OrmLiteSqliteOpenHelper,實現兩個抽象方法onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) 和 onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion),查看源碼可以知道OrmLiteSqliteOpenHelper是繼承了android裡內建的SqliteOpenHelper類,以上兩個抽象方法也是擴充自SqliteOpenHelper裡面的onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
public class DBHelper extends OrmLiteSqliteOpenHelper{ public DBHelper(Context context){ //用於通過註解+反射建立資料庫表 super(context, DB_NAME, null, VERSION_100); //用於通過讀取設定檔建立資料庫表 //super(context, DB_NAME, null, VERSION_101,R.raw.config); } @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { TableUtils.createTableIfNotExists(connectionSource, Account.class); } catch (SQLException e) { LogFactory.e(e); } } @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { if(oldVersion<VERSION_101){ fixVersion101() ; } if(oldVersion<VERSION_200){ fixVersion200() ; } }}
需要說的是在onUpgrade中如果對資料庫表有修改,則只能通過sql語句來進行,TableUtils在此時不能發揮作用。例:
void fixVersion200(){ try { String sql = "ALTER TABLE ‘"+TAB_ACCOUNT+"‘ ADD COLUMN "+DATE_ID+" INTEGER ;" ; getDao(Account.class).executeRaw(sql) ; } catch (SQLException e) { LogFactory.e(e); } }
2、OrmLiteSqliteOpenHelper中儲存著資料庫的連結,因此沒必要建立太多的OrmLiteSqliteOpenHelper執行個體,官方建議使用OpenHelperManager來對OrmLiteSqliteOpenHelper進行操作,通過OpenHelperManager.getHelper(Context context, Class<T> openHelperClass)則可以返回OrmLiteSqliteOpenHelper執行個體;或者通過setOpenHelperClass()然後再getHelper();再或者在res-string下面定義一個open_helper_classname,裡面制定類名,OrmLite架構會通過反射將其執行個體化;
3、最簡單的使用OpenHelperManager的方法是繼承OrmLiteBaseActivity,另外也提供了OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity,這些類裡面會自動管理OrmLiteSqliteOpenHelper.通過getHelper()則可以擷取;
4、如果不想使用官方提供的方法,那麼可以在自己的Activity裡面管理OrmLiteSqliteOpenHelper,一般是在onCreate()裡面建立,在onDestroy()裡面釋放掉;OpenHelperManager.getHelper()和releaseHelper()必須成對出現,不然可能出現意想不到的情況;
二、資料庫表配置
OrmLite提供了兩種方法配置表,一是通過註解,如果通過註解,因為OrmLite的註解是運行時的(Runtime),在反射的時候Method.equals()會消耗很多資源導致初始化資料變的很慢。因此才有了第二種方法--通過註解產生的設定檔。
1、通過註解
@DatabaseTable(tableName = "accounts")public class Account { @DatabaseField(id = true) private String name; @DatabaseField private String password; public Account() { // ORMLite needs a no-arg constructor } public Account(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
其中"@DatabaseTable"是配置資料表的,只有兩個屬性"tableName"(表名,預設為類名小寫)和"daoClass"(Dao管理類)。
"@DatabaseField"是配置表中的column的,屬性比較多,見官方文檔。
建立資料庫表則在繼承的OrmLiteSqliteOpenHelper的onCreate()中調用如下:
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { TableUtils.createTableIfNotExists(connectionSource, Account.class); } catch (SQLException e) { LogFactory.e(e); } }
2、通過註解加設定檔
註解部分如上。設定檔的產生需要Java工程中繼承OrmLiteConfigUtil
public class DatabaseConfigUtil extends OrmLiteConfigUtil { public static void main(String[] args) throws Exception { writeConfigFile("ormlite_config.txt"); }}
然後將生產的ormlite_config.txt檔案放到android工程的res-raw目錄下,執行個體化OrmLiteSqliteOpenHelper時則需要傳入raw資源id,
OrmLiteSqliteOpenHelper(Context context, String databaseName, CursorFactory factory, int databaseVersion,int configFileId)
那麼在建立資料表的時候OrmLite架構則會讀取設定檔而不會通過註解。以上組建組態檔案時可以把用到的model類放入到java工程中,然後在android工程裡面依賴java工程,如此可以只儲存一份modle類代碼,修改時很方便。
三、資料庫增刪改查
對資料庫表的增刪改查則通過OrmLiteSqliteOpenHelper.getDao(Class<T> clazz)擷取到不同的對象的Dao之後進行操作,具體見API文檔。OrmLiteSqliteOpenHelper裡面通過DaoManager對所有的Dao進行了緩衝,不必在別處儲存Dao了。
1、增
//儲存資料create(T data)//當不存在時儲存資料createIfNotExists(T data)//儲存或者更新資料createOrUpdate(T data)
2、刪
//刪除資料delete(T data)//根據ID刪除資料deleteById(ID id)//自訂的刪除請求,通過構建DeleteBuilder<T,ID>實現複雜的刪除deleteBuilder()
3、改
//更新對象update(T data)//更新對象IDupdateId(T data, ID newId)//返回UpdateBuilder<T,ID>實現複雜更新需求updateBuilder()
4、查
//根據ID查詢queryForId(ID id)//查詢所有資料queryForAll()//返回QueryBuilder<T,ID>自訂複雜的查詢需求queryBuilder()
以上DeleteBuilder, QueryBuilder, UpdateBuilder全部整合於StatementBuilder,因此得到XXBuilder之後可以通過where()設定條件,如下
QueryBuilder<Account, String> qb = accountDao.queryBuilder(); Where where = qb.where(); // the name field must be equal to "foo" where.eq(Account.NAME_FIELD_NAME, "foo"); // and where.and(); // the password field must be equal to "_secret" where.eq(Account.PASSWORD_FIELD_NAME, "_secret"); PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();
只是對於不同的XXBuilder需要調用不同的方法罷了,如delete()、query()、update()。更多詳情見API文檔。
android開源ORM架構OrmLite使用教程