Androrm - Android的ORM框架 - Androrm

openkk 12年前
     <p>Androrm 是 Android 平台上的一个对象关系映射框架,也就是我们常说的 ORM 框架。用于帮助你快速开发使用数据库的应用,封装了常用的表创建、对象读写和查询,通过将 Model 类映射到数据库表,直接对对象进行操作便可读写数据库。</p>    <p>下面我们给出一个简单的使用 Androrm 的教程:</p>    <p>1. 创建 Model 类</p>    <pre class="brush:java; toolbar: true; auto-links: false;">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();     }  }</pre>    <pre class="brush:java; toolbar: true; auto-links: false;">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);     }  }</pre>    <p>2. 创建数据库</p>    <p>接下来我们需要在应用的 onCreate 方法中创建数据库</p>    <pre class="brush:java; toolbar: true; auto-links: false;">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);</pre>    <p>3. 创建表关系</p>    <p>Androrm 有一个特殊的数据域——ForeignKeyField,通过它来定义外键关联</p>    <pre class="brush:java; toolbar: true; auto-links: false;">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);    }  }</pre>    <p>4. 插入数据</p>    <pre class="brush:java; toolbar: true; auto-links: false;">// 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);</pre>    <p>到此,整个简单的教程到此结束,更详细的关于 Androrm 的使用方法请参考<a href="/misc/goto?guid=4959499314967944562" rel="nofollow">文档</a>。</p>