Android ORM Series of Activeandroid

Source: Internet
Author: User
Tags java web sonatype

From the Java Web to Android students should know SSH or SSI, used to hibernate or mybatis, to go to Android after the easy to find the ORM is not feel very uncomfortable. In fact, there are many Orm in Android. Activeandroid sugarorm Siminov Greendao ormlite androrm

This article mainly introduces the usage of activeandroid. Students who have used Litepal will find that the use of these two frameworks is so similar.

Active record (Active Directory) is a typical way to name ORM implementations in a framework such as YII, rails, and so on. Active Android helps you manipulate sqlite in an object-oriented fashion. Configuration

Start by creating a new Android Studio project that joins activeandroid dependencies.

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 '
}

If you do not have a custom application class in your project, you can configure the application class in the framework directly in the manifest file

<manifest ...>
    <application android:name= "com.activeandroid.app.Application" ...>

        ...

    </application>
</manifest>

But it doesn't matter if you already have a custom application class in your project. Completes the initialization in the OnCreate method and completes the cleanup work in the Onterminate method.

public class App extends application {

    @Override public
    void OnCreate () {
        super.oncreate ();
        Activeandroid.initialize (this);

    }

    @Override public
    void Onterminate () {
        super.onterminate ();
        Activeandroid.dispose ();
    }

The corresponding function can be invoked to open the log before initialization

Activeandroid.setloggingenabled (TRUE);

Of course, you can also use the Initialize overload method to open.

Activeandroid.initialize (this,true);

The application is then specified in the manifest file. and configure the database name and database version under the application node.

<meta-data
            android:name= "aa_db_name"
            android:value= "store.db"/>
        <meta-data
            android: Name= "Aa_db_version"
            android:value= "1"/>

Of course you can also specify it in code, but it is recommended that you configure it in the manifest file

Configuration configuration=new Configuration.builder (This)
                . Setdatabasename ("Test.db")
                . Setdatabaseversion (1)
                . Create ();
Activeandroid.initialize (configuration,true);

Mr. Two entity class, let it inherit the model class, note that if you want to perform CRUD operations, you must inherit the model class. The table name can then be specified by the @table annotation, @Column Note To specify the column name.

@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 will find all of the model's subclasses by default, which may take a long time if we have many subclasses. To speed up the application, we can specify the model class directly in the manifest file, with multiple comma-separated

<meta-data
            android:name= "aa_models"
            android:value= "Cn.edu.zafu.activeandroiddemo.model.Item, Cn.edu.zafu.activeandroiddemo.model.Category "/>

Of course, you can also specify it in your code by configuration classes, but again, it is recommended that you configure it in the manifest file

Configuration configuration=new Configuration.builder (This)
                . Setdatabasename ("Test.db")
                . Setdatabaseversion (1)
                . Setmodelclasses (Item.class, Category.class)
                . Create ();
Activeandroid.initialize (configuration,true);

We see that category and item are a one-to-many relationship. To get multiple item sides from the category side, we add a method to the category,

Public list<item> items () {return
        Getmany (Item.class, "Category");
    }

If you want to specify a column index, add index = True to the corresponding annotation. Preservation and modification of data

Next, let's try to save a piece of data.

Category category=new Category ();
Category.setname ("book");
Category.save ();

Use the RE to look at the corresponding storage database directory, open the corresponding table, look at the data, it has indeed been saved in.


Look at the entity class, we do not have the ID of this attribute, why the table will be, in fact, this is the automatically generated primary key.

Now we're going to save a few item

Item item1=new item ();
Item1.setname ("Head of the Java");
Item1.setcategory (category);
Item1.save ();

Item item2=new item ();
Item2.setname ("Java core");
Item2.setcategory (category);
Item2.save ();

Look at the Item table, which automatically generates a foreign key for us, pointing to the previous category

If you want to modify the data, the corresponding class for the data operation, call the Save method. Support for Transactions

When you have a large number of data inserts, this is the time to use the transaction, Activeandroid is also supporting the transaction.

Activeandroid.begintransaction ();
try {
    //do something such as insert many data
    activeandroid.settransactionsuccessful ();
} finally {
    activeandroid.endtransaction ();
}
deletion of data

Delete by ID

Item.delete (item.class,1);

Of course you can also call delete directly

Item item = Item.load (Item.class, 1);
Item.delete ();

You can also manipulate the delete class

New Delete (). from (Item.class). WHERE ("Id =?", 1). Execute ();
Query for Data

Chained calls through SELECT, more query functions for readers to experience

List<model> Execute = new Select (). from (Item.class). WHERE ("Category =?", 1). by ("Name Desc"). Execute ();
Type serial number

Activeandroid supports many types by default, but if you want to customize the type of serialization, you can also inherit the Typeserializer class and rewrite the four methods inside.
For example, if we want to convert a date type to a long type, and then convert to a date type when reading, you can write this.

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); }
}

Of course, don't forget to register in the manifest file.

<meta-data
        android:name= "aa_serializers"
        android:value= " Cn.edu.zafu.activeandroiddemo.serializer.dateserializer,my.package.anothercustometypeserializer "/>

You can also register by code

Configuration configuration=new Configuration.builder (This)
                . Setdatabasename ("Test.db")
                . Setdatabaseversion (1)
                . Setmodelclasses (Item.class, Category.class)
                . Settypeserializers ( Dateserializer.class)
                . Create ();
Activeandroid.initialize (configuration,true);
Database Upgrades

If you need to upgrade your database, you first need to increase the database version number, which must be larger than before, that is, to increase the Aa_db_version property. If a new entity class is added, it is automatically added to the database. But if you want to change the existing table, such as adding a column, first you have to modify the entity class, and then you want to create the SQL statement file in the assets directory, the file name is the database version number, the suffix is SQL, which contains the upgrade statement, That is, what columns have you added. Like what

ALTER TABLE Item ADD COLUMN color INTEGER;

Keep it as 2.sql and put it in the assets directory to use the ContentProvider

Activeandroid supports ContentProvider, but the default identity column must be made up as shown below (the default identity column is ID).

@Table (name = "Category", id = basecolumns._id)

The value after the replication is _id

Of course, don't forget to configure it in the manifest file, and then you can use it.

<provider android:authorities= "Cn.edu.zafu.activeandroiddemo" android:exported= "false" Android:name= " Com.activeandroid.content.ContentProvider "/>
Source Download

http://download.csdn.net/detail/sbsujjbcy/9026793 RELATED LINKS https://github.com/codepath/android_guides/wiki/ Activeandroid-guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.