6
回答
Android 的数据库持久层框架 —— Androrm
注册华为云得mate10,2.9折抢先购!>>>   

Androrm 是 Android 平台上的一个对象关系映射框架,也就是我们常说的 ORM 框架。用于帮助你快速开发使用数据库的应用,封装了常用的表创建、对象读写和查询,通过将 Model 类映射到数据库表,直接对对象进行操作便可读写数据库。

下面我们给出一个简单的使用 Androrm 的教程:

1. 创建 Model 类

public class Book extends Model {

    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;

    // zero-argument constructor, that can be called
    // by androrm, to gather field information
    public Book() {
        super();

        // set up field with maxLength parameter
        mTitle = new CharField(80);
    }

    public getTitle() {
        return mTitle.get();
    }

}
public class Author extends Model {

    protected CharField mName;

    public Author() {
        super();

        mName = new CharField(80);
    }

    public void getName() {
         return mName.get();
    }

    public void setName(String name) {
         mName.set(name);
    }

}

2. 创建数据库

接下来我们需要在应用的 onCreate 方法中创建数据库

List<Class<? extends Model>> models = new ArrayList<Class<? extends Model>>();
models.add(Author.class);
models.add(Book.class);                                                     

DatabaseAdapter.setDatabaseName("a_database_name");
DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext());
adapter.setModels(models);

3. 创建表关系

Androrm 有一个特殊的数据域——ForeignKeyField,通过它来定义外键关联

public class Book extends Model {

    // fields visibility is set to protected,
    // so the Model class can access it
    protected CharField mTitle;

    // Link the Author model to the Book model.
    protected ForeignKeyField<Author> mAuthor;

    // zero-argument constructor, that can be called
    // by androrm, to gather field information
    public Book() {
        super();

        // set up field with maxLength parameter
        mTitle = new CharField(80);

        // initialize the foreign key relation
        mAuthor = new ForeignKeyField<Author>(Author.class);
    }

    public String getTitle() {
        return mTitle.get();
    }

   public void setAuthor(Author author) {
        mAuthor.set(author);
   }

}

4. 插入数据

// In your activity

Author author = new Author();
author.setName("My Author");
author.save(this);

Book book = new Book();
book.setName("Book name");
book.setAuthor(author);
book.save(this);

到此,整个简单的教程到此结束,更详细的关于 Androrm 的使用方法请参考文档

举报
红薯
发帖于7年前 6回/3K+阅
顶部