ORMLite是常用的一個ORM框架,她不止可以用在Android的sqlite數據庫,也可以使用她操作其他常見的數據庫。這兒是根據官方文檔抽取來的android用法。
一,添加依賴
導入ormlite-core.jar和ormlite-android.jar:下載jar
或者build.gradle中添加:
compile 'com.j256.ormlite:ormlite-android:5.0'
compile 'com.j256.ormlite:ormlite-core:5.0'
二,創建Bean類
1>類使用@DatabaseTable註解,標識一個表。
2>成員變量使用 @DatabaseField 註解,表示表中的列。
3>相關屬性設置可以查詢其依賴包中的DatabaseTable和Column註解類。持久化的數據類型可以查閱ORMLite官方文檔或庫源碼。
4>添加一個無參的構造函數。當執行查詢返回結果時,ORMLite會使用Java反射構造函數創建對象。
@DatabaseTable(tableName = "accounts")
public class Account {
//generatedId = true表示id主鍵自動生成
@DatabaseField(generatedId = true)
private int id;
//id = true表示這個列可以通過ID方法執行查詢,更新,刪除
@DatabaseField(id = true)
private String name;
//canBeNull = false表示不可以爲空
@DatabaseField(canBeNull = false)
private String password;
public Account() {
// ORMLite 需要一個無參構造器
}
public Account(String name, String password) {
this.name = name;
this.password = password;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
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;
}
}
三,創建數據庫
1>繼承OrmLiteSqliteOpenHelper 創建database helper;
2>在onCreate方法中調用TableUtils.createTable創建表,onUpgrade方法執行數據庫更新。TableUtils類提供了一些創建和刪除表的靜態方法,參考源代碼。
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TABLE_NAME = "sqlite.db";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 2);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Bean.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
}
}
四,創建DAO
在數據訪問對象(Data Access Objects (DAO))類中隔離數據庫操作,提供創建,刪除,更新,等等操作。每個表都對應一個DAO,每個DAO有兩個參數:使用DAO持久化數據的實體類和用來標示指定表中行的ID列,如果類中沒設置ID列,可以把對象或null作爲第二個參數。例如,在上面Account類中,“name”成員是ID列(id = true),所以ID列是字符串。
創建DAO的最簡單的方法是調用DaoManager.createDao(),這樣如果它們被內部ORMLite功能需要,可以重複使用,而不是重新創建(創建DAO很消耗資源,應該儘可能重複利用):
Dao<Account, String> accountDao =DaoManager.createDao(connectionSource, Account.class);
Dao<Order, Integer> orderDao =DaoManager.createDao(connectionSource, Order.class);
使用這種方式需要ConnectionSource參數,和實體類的Class對象,ConnectionSource參數可以通過OrmLiteSqliteOpenHelper的getConnectionSource()方法獲得:
ConnectionSource connectionSource = OrmLiteSqliteOpenHelper.getConnectionSource();
如果想要一個更好的類層次結構,或者在DAO中需要添加較多的方法,可以定義一個接口,繼承Dao接口,接口不是必須的,但這樣做可以減少耦合:
/** Account DAO ,具有字符串id (Account.name) */
public interface AccountDao extends Dao<Account, String> {
// 添加 DAO的方法
}
然後實現類繼承BaseDaoImpl並實現上面定義的接口:
/** JDBC implementation of the AccountDao interface. */
public class AccountDaoImpl extends BaseDaoImpl<Account, String>implements AccountDao {
// 這個構造器必須有
public AccountDaoImpl(ConnectionSource connectionSource)
throws SQLException {
super(connectionSource, Account.class);
}
}
要使用自定義DAO類的,需要到相應的實體類@DatabaseTable註解中添加daoClass參數:
@DatabaseTable(daoClass = AccountDaoImpl.class)
public class Account {
…
}
也可以在DatabaseHelper中調用OrmLiteSqliteOpenHelper.getDao創建:
private Dao<Account , Integer> accountDao;
public Dao<Account , Integer> getAccountDao() throws SQLException
{
if (AccountDao == null)
{
AccountDao = getDao(Account.class);
}
return accountDao;
}
五,運行時與SQL異常
默認情況下,大多數的DAO方法都會拋出SQLException,大部分的異常繼承RuntimeException,所以會需要大量的try … catch語句,出於這個原因,RuntimeExceptionDao包裝了調用DAO方法會出現的運行時異常SQL exceptions:
Dao<Account, String> dao = DaoManager.createDao(connectionSource, Account.class);
RuntimeExceptionDao<Account, String> accountDao = new RuntimeExceptionDao<Account, String>(dao);
或者直接使用其createDao方法:
RuntimeExceptionDao<Account, String> accountDao =RuntimeExceptionDao.createDao(connectionSource, Account.class);
在DatabaseHelper中可以調用OrmLiteSqliteOpenHelper.getRuntimeExceptionDao。
六,使用DAO
增
插入新的行到數據庫:
Account account = new Account();
account.name = "Jim Coakley";
accountDao.create(account);
查
如果對象具有註解聲明的id參數,那麼我們就可以使用其ID在數據庫中查找此對象:
Account account = accountDao.queryForId(name);
if (account == null) {
account not found handling …
}
改
如果改變對象的成員屬性,必須調用update()將改變更新到數據庫中:
account.password = "_secret";
accountDao.update(account);
刷新對象
如果數據空正使用的某個對象被其他實體改變,需要刷新這個對象,保證這個對象是實時的:
accountDao.refresh(account);
刪
刪除對象對應的數據庫中的行,一旦對象已經從數據庫中刪除,您可以繼續使用在內存中的該對象,但任何更新或刷新會失效:
accountDao.delete(account);
迭代
該DAO本身也是一個迭代器,因此可以直接遍歷數據庫數據中表的行:
// page through all of the accounts in the database
for (Account account : accountDao) {
System.out.println(account.getName());
}
這種方式必須遍歷數據庫中表的所有行,然後纔會關閉潛在的sql對象。 如果沒有通過循環遍歷所有的行,
ORMLite並不會關閉sql對象,數據庫的連接會被弱化並且只有GC回收纔會被關閉,這樣會導致程序Bug,所以最好使用
try…finally迭代器。以下for循環,是一個非常糟糕的代碼:
for (Account account : accountDao) {
if (account.getName().equals("Bob Smith")) {
// you can't return, break, or throw from here
return account;
}
}
也可以選擇直接使用迭代器,因爲for循環式並不總是最佳的。這樣允許使用try…finally,達到一種更優化的代碼:
CloseableIterator<Account> iterator = accountDao.closeableIterator();
try {
while (iterator.hasNext()) {
Account account = iterator.next();
System.out.println(account.getName());
}
} finally {
// close it at the end to close underlying SQL statement
iterator.close();
}
或者使用迭代包裝器,for循環之後仍然可以關閉:
CloseableWrappedIterable<Account> wrappedIterable =
accountDao.getWrappedIterable();
try {
for (Account account : wrappedIterable) {
…
}
} finally {
wrappedIterable.close();
}
七,使用OpenHelperManager
DatabaseHelper可能在App或多個Activity的線程中被多次實例化使用,如果同時有多個對象,可能會出現過時的數據和意外的結果。所以建議使用OpenHelperManager管理DatabaseHelper的使用:
private DatabaseHelper databaseHelper = null;
private void releaseHelper() {
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
}
private DatabaseHelper getHelper() {
if (databaseHelper == null) {
databaseHelper =
OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}
還可以讓Activity繼承OrmLiteBaseActivity,OrmLiteBaseActivity對OpenHelperManager的使用做了進一步封裝,還有OrmLiteBaseListActivity, OrmLiteBaseService, OrmLiteBaseTabActivity等,不過一般不這麼做。但是可以在使用OpenHelperManager的時候拿來參考。
然後通過databaseHelper操作數據庫:
Dao<Account, String> accountDao = getHelper().getAccountDao();
Account account = new Account ();
account.setName("one");
account.setPassword("123");
accountDao.create(account);
八,ORMLite外鍵
ORMLite支持外鍵的概念,既一個對象的一個或者多個屬性保存在相同數據庫中其他表中。比如數據庫中有一個Order對象,每個Order對象都對應一個Account對象,然後就說Order(是一個表)對象的Account(也是一個表)成員有外鍵屬性。id成員在表創建的時候會生成”account_id”列:
@DatabaseTable(tableName = "orders")
public class Order {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField(canBeNull = false, foreign = true)
private Account account;
…
}
當創建有外鍵屬性成員的對象(Order)時,外鍵對象(Account)不會被自動創建(Account表不會自動創建)。如果外鍵對象(Account對象)在數據庫中有generated id(Order對象有 id成員),應該在創建引用這個對象(Order對象有Account成員)的對象(Order對象)之前創建外鍵對象(Account表):
Account account = new Account("Jim Coakley");
accountDao.create(account);
// 這時會創建一個account對象,並且設置generated ids
// 現在用order設置account,創建並插入account表
Order order = new Order("Jim Sanders", 12.34);
order.setAccount(account);
…
orderDao.create(order);
某些情況下如果希望外鍵自建,可以在外鍵(account)的註解中設置foreignAutoCreate參數。
當你查詢一個Order時,會獲得一個account對象,這個對象只有id屬性被設定了值,其他屬性都是默認值(null, 0, false, etc.)。如果需要使用這個account對象的其他值,則必須調用accountDao類的refresh方法獲得這個Account對象的屬性:
Order order = orderDao.queryForId(orderId);
System.out.println("Account-id on the order should be set: " +
order.account.id);
// 此時 order.account.name爲null
System.out.println("But other fields on the account should not be set: "
+ order.account.name);
// 用AccountDao刷新一下account
accountDao.refresh(order.getAccount());
System.out.println("Now the account fields will be set: " +
order.account.name);
也可以在註解中添加foreignAutoRefresh參數值設置自動刷新外鍵對象的數據。
有不同的方式查詢外鍵的參數值,比如查詢匹配某個account的所有Order,通過ID參數的成員和account的name查詢:
// query for all orders that match a certain account
List<Order> results =
orderDao.queryBuilder().where().
eq("account_id", account.getName()).query();
也可以讓ORMLite從該account中自動提取id獲得:
// ORMLite will extract and use the id field internally
List<Order> results =
orderDao.queryBuilder().where().
eq("account_id", account).query();
九,外鍵集合
上面說了Account是Order的外鍵,如果一個Account對象對應多個Order對象,則可以將其以成員的形式通過 @ForeignCollectionField註解以以下形式添加到Account中去:
public class Account {
…
@ForeignCollectionField(eager = false)
ForeignCollection<Order> orders;
…
}
成員類型只可以使用ForeignCollection< T> 或 Collection< T>。註解參數可以查閱庫中的ForeignCollectionField類。
當改變了Collection中的order時,需要調用update在數據庫中更新它:
for (Order order : account.orders()) {
// 如果改變了order的某些成員
order.setAmount(123);
// 必須在數據庫中更新account
account.orders.update(order);
}
十,事務
當對數據庫有較多的執行動作時,用事務處理比較好,圖個方便,下段代碼摘自ormlite的事務使用
private boolean doBatchInTransaction(final List<T> list, final int batchType) {
boolean doBatch = false;
ConnectionSource connectionSource = ormLiteDao.getConnectionSource();
TransactionManager transactionManager = new TransactionManager(connectionSource);
Callable<Boolean> callable = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return doBatch(list, batchType);
}
};
try {
doBatch = transactionManager.callInTransaction(callable);
} catch (SQLException e) {
LogUtil.e(e);
}
return doBatch;
}
private boolean doBatch(List<T> list, int batchType) {
int result = 0;
try {
for (T t : list) {
switch (batchType) {
case DaoOperation.INSERT:
result += ormLiteDao.create(t);
break;
case DaoOperation.DELETE:
result += ormLiteDao.delete(t);
break;
case DaoOperation.UPDATE:
result += updateIfValueNotNull(t);
break;
default:
LogUtil.w("no this type.");
break;
}
}
} catch (SQLException e) {
LogUtil.e(e);
}
return result == list.size();
}
十一,更新數據庫
更新app時,可能會修改現有的數據庫,這時就需要在 創建的DatabaseHelper的onUpgrade方法中進行一些工作了。比如在表中增加一列,可以在onUpgrade方法中這麼做:
Dao<Account, Integer> dao = getHelper().getAccountDao();
// 在表account中增加 "age" 列
dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
所有能做的就是重新命名錶名和添加新列,不要重命名或刪除列或更改列的屬性。
最常用的,是根據版本條件更改數據庫:
if (oldVersion < 2) {
// we added the age column in version 2
dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
}
if (oldVersion < 3) {
// we added the weight column in version 3
dao.executeRaw("ALTER TABLE `account` ADD COLUMN weight INTEGER;");
}
或者:
dao.executeRaw(
"ALTER TABLE `account` ADD COLUMN hasDog BOOLEAN DEFAULT 0;");
dao.updateRaw("UPDATE `account` SET hasDog = 1 WHERE dogCount > 0;");
這兒用到了數據庫語句,可以查閱sqlite官方文檔。
更多請參考 ORMLite官方文檔 ,