從Java Web轉到android的同學應該都知道ssh或者ssi,用慣了hibernate或者mybatis,轉到android後找不到順手的orm是不是感覺很不自在。其實android 中的orm還是很多的。 ActiveAndroid SugarORM Siminov greenDAO ORMLite androrm cupboard
本篇文章主要介紹一下ActiveAndroid的用法。用過LitePal的同學會發現,這兩個架構的用法是如此的相似。
Active Record(活動目錄)是Yii、Rails等架構中對ORM實現的典型命名方式。Active Android 協助你以物件導向的方式來操作SQLite。 配置
首先建立一個android studio項目,加入ActiveAndroid的依賴。
repositories { mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.1' compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'}
如果你的項目中還沒有自訂的Application類,那麼可以直接在manifest檔案中組態架構中的Application類
<manifest ...> <application android:name="com.activeandroid.app.Application" ...> ... </application></manifest>
但是如果你項目中已經有了一個自訂的Application類,那麼也沒有關係。在onCreate方法中完成初始化,在onTerminate方法中完成清理工作。
public class App extends Application { @Override public void onCreate() { super.onCreate(); ActiveAndroid.initialize(this); } @Override public void onTerminate() { super.onTerminate(); ActiveAndroid.dispose(); }}
在初始化之前可以調用對應函數開啟日誌
ActiveAndroid.setLoggingEnabled(true);
當然也可以用initialize的重載方法開啟。
ActiveAndroid.initialize(this,true);
然後在資訊清單檔中指定該Application。並在application結點下設定資料庫名和資料庫版本
<meta-data android:name="AA_DB_NAME" android:value="Store.db"/> <meta-data android:name="AA_DB_VERSION" android:value="1"/>
當然你也可以在代碼中指定,不過建議在資訊清單檔中配置
Configuration configuration=new Configuration.Builder(this) .setDatabaseName("test.db") .setDatabaseVersion(1) .create();ActiveAndroid.initialize(configuration,true);
先產生兩個實體類,讓其繼承Model 類,注意,如果要進行CRUD操作的話必須繼承Model 類。然後通過@Table註解可以指定表名,@Column註解來指定列名。
@Table(name = "Category")public class Category extends Model { @Column(name = "Name") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Category{" + "name='" + name + '\'' + '}'; }}@Table(name = "Item")public class Item extends Model { @Column(name = "Name") public String name; @Column(name = "Category") public Category category; public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } @Override public String toString() { return "Item{" + "name='" + name + '\'' + ", category=" + category + '}'; }}
ActiveAndroid預設會尋找所有Model的子類,可能會花去很長的時間如果我們有很多子類。為了加快應用的啟動速度,我們可以在資訊清單檔中直接指定model類,多個用逗號分隔
<meta-data android:name="AA_MODELS" android:value="cn.edu.zafu.activeandroiddemo.model.Item, cn.edu.zafu.activeandroiddemo.model.Category" />
當然你也可以在代碼中通過Configuration類來指定,不過同樣的,還是建議在資訊清單檔中配置
Configuration configuration=new Configuration.Builder(this) .setDatabaseName("test.db") .setDatabaseVersion(1) .setModelClasses(Item.class, Category.class) .create();ActiveAndroid.initialize(configuration,true);
我們看到Category 和 Item是一對多的關係。為了從Category方得到多的Item一方,我們在Category中增加一個方法,
public List<Item> items() { return getMany(Item.class, "Category"); }
如果你要指定某一列為索引,在對應的註解上加上index = true即可。 資料的儲存和修改
接下來,我們來儲存一條資料試試看。
Category category=new Category();category.setName("book");category.save();
用RE查看一下對應的存資料庫的目錄,開啟對應的表,看下資料,確實已經存進去了。
看下實體類,我們並沒有id這個屬性,為什麼表中會有呢,其實這是自動產生的主鍵。
現在我們來儲存幾條item
Item item1=new Item();item1.setName("head first java");item1.setCategory(category);item1.save();Item item2=new Item();item2.setName("java core");item2.setCategory(category);item2.save();
看下Item表,其為我們自動產生了外鍵,指向了之前的category
如果要修改資料的話,對對應的類進行資料操作,調用save方法即可。 事務的支援
當你有大量的資料插入時,這時候就要用到事務,ActiveAndroid也是支援事務的。
ActiveAndroid.beginTransaction();try { //do something such as insert many data ActiveAndroid.setTransactionSuccessful();}finally { ActiveAndroid.endTransaction();}
資料的刪除
根據id刪除
Item.delete(Item.class,1);
當然你也可以直接調用delete
Item item = Item.load(Item.class, 1);item.delete();
也可以通過Delete類進行操作
new Delete().from(Item.class).where("Id = ?", 1).execute();
資料的查詢
通過Select進行鏈式調用,更多查詢的函數請讀者自己體驗
List<Model> execute = new Select().from(Item.class).where("Category = ?", 1).orderBy("name desc").execute();
類型序號
ActiveAndroid 預設支援了很多類型,但是如果你想自訂處理序列化的類型,你也可以繼承TypeSerializer 類,重寫裡面的四個方法即可。
比如我們要將Date類型轉換為long類型儲存,讀取的時候又要轉換為Date類型,則可以這樣編寫。
public class DateSerializer extends TypeSerializer { @Override public Class<?> getDeserializedType() { return Date.class; } @Override public Class<?> getSerializedType() { return Long.class; } @Override public Long serialize(Object data) { if (data == null) { return null; } return ((Date) data).getTime(); } @Override public Date deserialize(Object data) { if (data == null) { return null; } return new Date((Long) data); }}
當然別忘了在資訊清單檔中註冊
<meta-data android:name="AA_SERIALIZERS" android:value="cn.edu.zafu.activeandroiddemo.serializer.DateSerializer,my.package.AnotherCustomeTypeSerializer"/>
同樣也可以通過代碼註冊
Configuration configuration=new Configuration.Builder(this) .setDatabaseName("test.db") .setDatabaseVersion(1) .setModelClasses(Item.class, Category.class) .setTypeSerializers(DateSerializer.class) .create();ActiveAndroid.initialize(configuration,true);
資料庫升級
如果需要升級資料庫,首先需要增加資料庫版本號碼,必須比之前的大,即增大AA_DB_VERSION 屬性。如果增加了新的實體類,它會自動增加到資料庫中,但是如果你想改變已經存在的表,比如增加一列,首先你要修改實體類,然後你要在assets目錄下建立sql語句的檔案,檔案名稱為資料庫版本號碼,尾碼是sql,裡面寫著升級語句,即你增加了什麼列等。比如
ALTER TABLE Item ADD COLUMN color INTEGER;
將其保持為2.sql,放到assets目錄下 使用ContentProvider
ActiveAndroid支援ContentProvider,但是必須複寫預設的識別欄位如下所示(預設識別欄位是ID)。
@Table(name = "Category",id = BaseColumns._ID)
複寫後的值是_id
當然不要忘記在資訊清單檔中配置,之後你就可以使用了。
<provider android:authorities="cn.edu.zafu.activeandroiddemo" android:exported="false" android:name="com.activeandroid.content.ContentProvider" />
源碼下載
http://download.csdn.net/detail/sbsujjbcy/9026793 相關連結 https://github.com/codepath/android_guides/wiki/ActiveAndroid-Guide