zoukankan      html  css  js  c++  java
  • ActiveAndroid 管理数据库

    ActiveAndroid算是一个轻量级的ORM框架(对象关系映射)。ActiveAndroid允许你保存和检索SQLite数据库记录,而无需编写一个单独的SQL语句。每个数据库记录被包裹整齐地归为一类,如save()和delete()的方法。ActiveAndroid照顾所有的设置和凌乱的东西,所有的配置,只需几个简单的步骤。

    工程配置

    • 在AndroidManifest.xml中需要添加数据库名和版本号
    1. <meta-data
    2. android:name="AA_DB_NAME"
    3. android:value="Pickrand.db" />
    4. <meta-data
    5. android:name="AA_DB_VERSION"
    6. android:value="1" />

    如果这两个都不写的话,默认会是Application.db,库版本号为1。

    • 在Application中初始化
      可以继承com.activeandroid.app.Application,可以在自己的Application里初始化,看com.activeandroid.app.Application文件就明白了:
    1. public class Application extends android.app.Application {
    2. @Override
    3. public void onCreate() {
    4. super.onCreate();
    5. ActiveAndroid.initialize(this);
    6. }
    7. @Override
    8. public void onTerminate() {
    9. super.onTerminate();
    10. ActiveAndroid.dispose();
    11. }
    12. }

    所以如果不继承只需要在自己的Application 添加ActiveAndroid.initialize(this)和
    ActiveAndroid.dispose()的操作即可。

    实际应用

    创建Model类

    1. @Table(name = "Items")
    2. public class Item extends Model {
    3. // 这样可以避免重复
    4. @Column(name = "remote_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    5. public int remoteId;
    6. @Column(name = "Name")
    7. public String name;
    8. @Column(name = "Category")
    9. public Category category;
    10. // 确保每个model类中都有一个默认的构造方法
    11. public Item(){
    12. super();
    13. }
    14. public Item(String remoteId, String name, Category category){
    15. super();
    16. this.remoteId = remoteId;
    17. this.name = name;
    18. this.category = category;
    19. }
    20. }

    这个Item类中包含了一个Category类型的对象

    1. @Table(name = "Categories")
    2. public class Category extends Model {
    3. @Column(name = "remote_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    4. public int remoteId;
    5. @Column(name = "Name")
    6. public String name;
    7. @Column(name = "Entry")
    8. public Entry entry;
    9. public Category(){
    10. super();
    11. }
    12. public void saveEntry() {
    13. if (entry != null) {
    14. entry.save();
    15. }
    16. }
    17. public List<Item> data;
    18. // 使用外键,实现一对多存储
    19. public List<Item> items() {
    20. data = getMany(Item.class, "Category");
    21. }
    22. }

    这其中又包含了一个Entry对象

    1. @Table(name = "Entrys")
    2. public class Entry extends Model {
    3. @Column(name = "Name")
    4. public String name;
    5. }

    具体的model类其实是根据实际情况来写的,这里只写最简单的。在数据库应用中,我们涉及的无外乎是增删改查,这里以一个简单的例子来研究一下。

    实际项目中,我们经常会遇到这样的情况,一个类Category 中包含一个Entry对象,包含一个List<Item>对象,一个String对象。

    模拟一下数据:

    1. List<Category> Categorys = new ArrayList<Category>();
    2. List<Item> Items = new ArrayList<Item>();
    3. for (int i = 0; i < 100; i++) {
    4. Category restaurants = new Category();
    5. restaurants.name = "Category " + i;
    6. Entry entry = new Entry();
    7. entry.name = "entry " + i;
    8. restaurants.entry = entry;
    9. Categorys.add(restaurants);
    10. for (int j = 0; j < 3; j++) {
    11. Item item = new Item();
    12. item.name = "Item " + i + " from " + "Category " + i;
    13. item.category = restaurants;
    14. Items.add(item);
    15. }
    16. }

    在这个框架中,一个对象中包含一个List对象,其实就是把List对象全部存到另一个表里,通过外键来关联。

    通过事务,批量添加进数据库。

    1. ActiveAndroid.beginTransaction();
    2. try {
    3. int len = Categorys.size();
    4. for (int i = 0; i < len; i++) {
    5. Categorys.get(i).saveEntry();
    6. Categorys.get(i).save();
    7. }
    8. len = Items.size();
    9. for (int i = 0; i < len; i++) {
    10. Items.get(i).save();
    11. }
    12. ActiveAndroid.setTransactionSuccessful();
    13. } finally {
    14. ActiveAndroid.endTransaction();
    15. }

    这里需要注意的是Item类中包含Category对象,Category类中包含Entry对象。必须先保存Entry对象,Entry对象会得到一个Id,然后才能存储Category对象,否则Category对象中的Entry对象就会为null。这部分逻辑可以查看Model类中save()方法的源码:

    1. else if (ReflectionUtils.isModel(fieldType)) {
    2. values.put(fieldName, ((Model) value).getId());
    3. }

    如果Entry对象不先存储,Id是为null的。Entry与Category关联的依赖就是Entry
    的Id。所以执行完Categorys.get(i).saveEntry()后才执行Categorys.get(i).save()其后才执行Item的存储,这时候Category对象都已经有了Id,Item会自动关联。

    1. Item item = Item.load(Item.class, 1);
    2. item.delete();
    3. // 或者
    4. new Delete().from(Item.class).where("remote_id = ?", 1).execute();

    批量删除就用事务。

    先看下Model类源码152行:

    1. if (mId == null) {
    2. mId = db.insert(mTableInfo.getTableName(), null, values);
    3. }else {
    4. db.update(mTableInfo.getTableName(), values, idName+"=" + mId, null);
    5. }

    很明显,如果mId不存在就会去数据库创建这跳数据,而如果数据存在的话,那就是更新了。所以,更改数据后直接执行save方法即可。

    1. public static List<Item> getAll(Category categoryint num) {
    2. return new Select()
    3. .from(Item.class)
    4. .where("Category = ?", category.getId())
    5. .orderBy("Name ASC")
    6. .limit(num)
    7. .execute();
    8. }

    执行一个Select方法,指定表Item.class,限定条件where("Category = ?", category.getId()),排序为orderBy("Name ASC"),取出个数为limit(num)
    当然还支持其他非常多的指令

    • offset
    • as
    • desc/asc
    • inner/outer/cross join
    • group by
    • having
      这个就根据自己需求了。

    在查询Category数据中,因为每个对象中包括了一个List<Item>对象,所以,我们需要在查询出Category对象后,在把关联的List表查询一遍。

    1. ActiveAndroid.beginTransaction();
    2. try {
    3. List<Category> testCategory = new Select().from(Category.class).limit(20).execute();
    4. if (testCategory != null) {
    5. int len = testCategory.size();
    6. for (int i = 0; i < len; i++) {
    7. testCategory.get(i).items();
    8. }
    9. }
    10. ActiveAndroid.setTransactionSuccessful();
    11. } finally {
    12. ActiveAndroid.endTransaction();
    13. }

    如此执行完,对象中的data就可以直接用了。

    总结

    作为一个轻量级的ORM框架,在快速开发中,用起来还是很方便的,比ORMLite要简单一些,但某些细节不如ORMLite更强大,不如对象中包含对象时,ORMLite中可以有参数设定自动创建,而不是需要我们手动执行下sava,也许在ActiveAndroid中也可以这样,但目前我没搞明白注解中另几个属性的意思。整体性能经测试(100条Category数据,300条Item数据,100条Entry数据)存储耗时1.1s-1.2s,与ORMLite是持平的,但也许是测试数据太小了,没有说服性,有时间可以进行10w条数据的测试。

  • 相关阅读:
    【高并发】面试官问我:为什么局部变量是线程安全的?
    Java中的String到底占用多大的内存空间?你所了解的可能都是错误的!!
    【高并发】学好并发编程,关键是要理解这三个核心问题
    【高并发】高并发分布式锁架构解密,不是所有的锁都是分布式锁!!
    12张图带你彻底理解分布式事务产生的场景和解决方案!!
    【高并发】面试官:讲讲高并发场景下如何优化加锁方式?
    【高并发】秒杀系统架构解密,不是所有的秒杀都是秒杀(升级版)!!
    十一长假我肝了这本超硬核PDF,现决定开源!!
    一文搞懂PV、UV、VV、IP及其关系与计算
    我把这个贼好用的Excel导出工具开源了!!
  • 原文地址:https://www.cnblogs.com/ran2013/p/4606294.html
Copyright © 2011-2022 走看看