日期:2014-05-16  浏览次数:20331 次

Android数据库存取对象--CupBoard
有一段时间没来写点什么了,这次来给大家介绍一个能在数据库中存取实体对象的库:cupboard。
在Android开发中,使用数据库存取数据时,我们最先而且必定要使用的就是 SQLite 了,相信现在还有很多开发者使用数据库存取时
使用的是最基础的一些语句,如《android sqlitedatabase 应用》一文中所介绍的一样。当然,这样写并没有什么不妥。现在随着学习的
深入,本人已经不再使用这种方式来进行数据库的操作,而是改用GreenDao这个开源库。在Android开发上来说,它可能是最快的ORM,
并且性能高、占用内存小。它将数据对象映射到数据库表中,然后你可以使用它提供的一个简单面向对象API对它进行增删改查。具体有关
GreenDao的使用不是本文内容,暂不介绍。下面继续本文的重点:CupBoard
CupBoard,它的主要目标就是在SQLite数据库中存储Objects。接下来为您详细介绍它是如何使用尽可能少的SQL语句来进行存储对象

的。不管你之前是使用SQLiteOpenHelper还是第三方库来进行数据库操作,本文都非常适合你。

public class Book {
   public Long _id;
   public String title;
   public Author author;
   public Date publishDate;
}
接下来,我们将Book这个实体存储到数据库中。(变量名对应数据库中的字段名)

使用CupBoard来操作数据库,要用withDatabase()这个方法,并且CupBoard要求须提前将实体注入到SQLiteOpenHelper,我们使用

static initializer block 在这里也许是最好的方法。下面看例子: 

首先创建数据库:

public class CupboardSQLiteOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "myapp.db";
    private static final int DATABASE_VERSION = 1;

    static {
        // register our models
        cupboard().register(Book.class);
        cupboard().register(Author.class);
    }

    public CupboardSQLiteOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // this will ensure that all tables are created
        cupboard().withDatabase(db).createTables();
        // add indexes and other database tweaks
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // this will upgrade tables, adding columns and new tables.
        // Note that existing columns will not be converted
        cupboard().withDatabase(db).upgradeTables();
        // do migration work
    }
}
       需要注意的是, 从上面代码看到,我们只添加了一个static初始化块和 

         cupboard().withDatabase(db).createTables(); 

         cupboard().withDatabase(db).upgradeTables();

而没有任何的继承(extends)和重写(override)。如何你使用的不是SQLiteOpenHelper,同样你也要添加一个static初始化块和update、upgrade

存储Objects

存储数据时使用withDatabase(db).put()方法。

Book book = ...
long id = cupboard().withDatabase(db).put(book);

读取Objects

通过id获得一条数据:读取id为12的数据对象,如果没有返回null。

Book book = cupboard().withDatabase(db).get(Book.class, 12L);
  我们还可以使用query()来遍历数据库

// get the first book in the result
Book book=cupboard().withDatabase(db).query(Book.class).get();
// Get the cursor for this query
Cursor books=cupboard().withDatabase(db).query(Book.class).getCursor();
try{
     // Iterate books
     QueryResultIterable<Book>itr=cupboard().withDatabase(db).query(Book.class).iterate();
     for(Book book:itr){
      // do somet