Android輕量級ORM框架ActiveAndroid入門教程
ActiveAndroid算是一個輕量級的ORM框架,簡單地通過如save()和delete()等方法來做到增刪改查等操作。配置起來也還算簡單。
開始
在AndroidManifest.xml中我們需要添加這兩個
AA_DB_NAME
(這個name不能改,但是是可選的,如果不寫的話 是默認的"Application.db"這個值)-
AA_DB_VERSION
(optional – defaults to 1)...
這個<application>
是必須指定的,但你也可以使用自己的Application,繼承自com.activeandroid.app.Application
public class MyApplication extends com.activeandroid.app.Application { ...
如果你不想或者不能繼承com.activeandroid.app.Application
的話,那么就這樣
public class MyApplication extends SomeLibraryApplication { @Override public void onCreate() { super.onCreate(); ActiveAndroid.initialize(this); } @Override public void onTerminate() { super.onTerminate(); ActiveAndroid.dispose(); } }
ActiveAndroid.initialize(this);
做初始化工作,ActiveAndroid.dispose();
做清理工作
創建數據庫模型
我們使用@Table(name = "Items")
來表示表,使用@Column(name = "Name")
來表示列,ActiveAndroid會使用自增長的ID作為主鍵,然后按照注解描述,將類對應映射為數據庫表。
@Table(name = "Items") public class Item extends Model { @Column(name = "Name") public String name; @Column(name = "Category") public Category category; public Item(){ super(); } public Item(String name, Category category){ super(); this.name = name; this.category = category; } }
依賴關系的數據庫表
假如Item和Category是多對一的關系,那么我們可以這樣子創建他們的類
@Table(name = "Items") public class Item extends Model { @Column(name = "Name") public String name; @Column(name = "Category") public Category category; } <!-- lang: java --> @Table(name = "Categories") public class Category extends Model { @Column(name = "Name") public String name; public List<Item> items() { return getMany(Item.class, "Category"); } }
如何保存和更新數據到數據庫
單挑插入
保存Category對象
Category restaurants = new Category(); restaurants.name = "Restaurants"; restaurants.save();
分配了一個category并且保存到數據庫
Item item = new Item(); item.category = restaurants; item.name = "Outback Steakhouse"; item.save();
批量插入
如果你要批量插入數據,最好使用事務(transaction)。
ActiveAndroid.beginTransaction(); try { for (int i = 0; i < 100; i++) { Item item = new Item(); item.name = "Example " + i; item.save(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); }
使用事務的話只用了 40ms,不然的話需要4秒。
刪除記錄
我們有三種方式刪除一條記錄
Item item = Item.load(Item.class, 1); item.delete(); <!-- lang: java --> Item.delete(Item.class, 1); <!-- lang: java --> new Delete().from(Item.class).where("Id = ?", 1).execute();
很簡單吧
查詢數據庫
作者將查詢做的非常像SQLite的原生查詢語句,幾乎涵蓋了所有的指令 com.activeandroid.query包下有以下類
- Delete
- From
- Join
- Select
- Set
- Update
我們舉例說明吧
public static Item getRandom(Category category) { return new Select() .from(Item.class) .where("Category = ?", category.getId()) .orderBy("RANDOM()") .executeSingle(); }
對應的sqlite查詢語句就是 select * from Item where Category = ? order by RANDOM()
當然還支持其他非常多的指令
- limit
- offset
- as
- desc/asc
- inner/outer/cross join
- group by
- having 等等
大家可以在ActiveAndroid項目下的tests工程找到測試用例,有非常多詳細的描述。
來自:http://linkyan.com/2013/05/about-activeandroid/