Android Open Source ORM Framework Ormlite Use tutorial

Source: Internet
Author: User

Ormlite is a lightweight object-relational mapping package developed by the Java language. There are ormlite-core,ormlite-android,ormlite-examples on GitHub, which are the main libraries, Android dependencies and some tutorials.

First, prepare

In order to use Ormlite on Android, we need to download Ormlite-core.jar and Ormlite-android.jar into the project directory and then:

1. Create a class to inherit ormlitesqliteopenhelper, implement two abstract methods OnCreate (Sqlitedatabase sqlitedatabase, Connectionsource Connectionsource) and Onupgrade (Sqlitedatabase database, Connectionsource connectionsource, int oldversion, int NewVersion), see the source code can know Ormlitesqliteopenhelper is inherited from the Android Sqliteopenhelper class, The above two abstract methods are also extended from Sqliteopenhelper inside the OnCreate (Sqlitedatabase db) and Onupgrade (sqlitedatabase db, int oldversion, int NewVersion);

 Public classDBHelperextendsormlitesqliteopenhelper{ PublicDBHelper (Context context) {//for creating database tables with annotation + reflection        Super(Context, Db_name,NULL, version_100); //to create a database table by reading a configuration file//Super (context, db_name, NULL, version_101,r.raw.config);} @Override Public voidonCreate (sqlitedatabase database, Connectionsource connectionsource) {Try{tableutils.createtableifnotexists (Connectionsource, account.class); } Catch(SQLException e) {logfactory.e (e); }} @Override Public voidOnupgrade (sqlitedatabase database, Connectionsource Connectionsource,intOldversion,intnewversion) {        if(oldversion<version_101)        {fixVersion101 (); }        if(oldversion<version_200)        {fixVersion200 (); }    }}

What needs to be said is that in Onupgrade, if the database table has been modified, it can only be done by SQL statements, tableutils at this time can not play a role. Cases:

void fixVersion200 () {        try  {            = "ALTER TABLE '" +tab_account+ "' ADD COLUMN ' +date_id+" INTEGER; "  ;            Getdao (account. class ). Executeraw (SQL);         Catch (SQLException e) {            logfactory.e (e);        }    }

2, Ormlitesqliteopenhelper Save the database link, so there is no need to create too many ormlitesqliteopenhelper instances, The official recommendation is to use Openhelpermanager to operate the Ormlitesqliteopenhelper through Openhelpermanager.gethelper (context context, class<t > Openhelperclass) can return Ormlitesqliteopenhelper instances, or Setopenhelperclass () and then Gethelper () , or define a open_helper_classname under Res-string, which defines the class name, and the Ormlite framework instantiates it by reflection;

3, the simplest way to use Openhelpermanager is to inherit Ormlitebaseactivity, also provides ormlitebaselistactivity, Ormlitebaseservice, and Ormlitebasetabactivity, these classes will automatically manage the ormlitesqliteopenhelper. Through Gethelper () can be obtained;

4, if you do not want to use the official method, then you can manage the ormlitesqliteopenhelper in their activity, usually in the OnCreate () inside the creation, in OnDestroy () released ; Openhelpermanager.gethelper () and Releasehelper () must appear in pairs, otherwise unexpected circumstances may occur;

Second, the database table configuration

Ormlite provides two ways to configure the table, one is through annotations, if through annotations, because Ormlite annotations are runtime (runtime), when reflected method.equals () consumes a lot of resources causing the initialization data to become very slow. Thus there is the second method-the configuration file generated by the annotations.

1. Through annotations

@DatabaseTable (TableName = "Accounts") Public classAccount {@DatabaseField (id=true)    PrivateString name; @DatabaseFieldPrivateString password;  PublicAccount () {//Ormlite needs a no-arg constructor    }     PublicAccount (string name, string password) { This. Name =name;  This. Password =password; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}

where "@DatabaseTable" is the configuration data table, only two properties "tableName" (table name, default to the class name lowercase) and "Daoclass" (DAO Management Class).

"@DatabaseField" is the column in the configuration table, with more properties, see official documentation.

The creation of the database table is called in the OnCreate () of the inherited Ormlitesqliteopenhelper, as follows:

 Public void onCreate (sqlitedatabase database,            connectionsource connectionsource) {        try  {            Tableutils.createtableifnotexists (Connectionsource, account. ) class );         Catch (SQLException e) {            logfactory.e (e);        }    }

2. Add config file via annotations

The annotations section is as above. Configuration file generation requires Java engineering to inherit Ormliteconfigutil

 Public class extends Ormliteconfigutil {  publicstaticvoidthrows  Exception {    Writeconfigfile ("Ormlite_config.txt");}  }

The production Ormlite_config.txt file is then placed in the Android project's Res-raw directory, and the raw resource ID is passed in when the Ormlitesqliteopenhelper is instantiated.

int Databaseversion, int Configfileid)

The Ormlite framework reads the configuration file and does not pass annotations when the data table is created. The above configuration file can be used to put the model class into the Java project, and then in the Android project relies on Java engineering, so you can only save a copy of the Modle class code, modification is very convenient.

Third, database additions and deletions to check

The additions and deletions to the database tables are then manipulated by Ormlitesqliteopenhelper.getdao (Class<t> Clazz) to the different objects of DAO, as described in the API documentation. Ormlitesqliteopenhelper all the DAO is cached through Daomanager, and it is not necessary to save the DAO elsewhere.

1, increase

// Save Data Create (T data) // save data when not present createifnotexists (T data) // Save or update createorupdate (T data)

2. By deleting

// Delete Data Delete (T data) // delete data by ID Deletebyid (ID ID) // Custom Delete requests to implement complex deletions by building deletebuilder<t,id>

3, change

// Updating Objects Update (T data) // Update Object ID UpdateID (T data, ID newId) // return to updatebuilder<t,id> for complex update requirements Updatebuilder ()

4. Check

// Query by ID Queryforid (ID ID) // Querying all data Queryforall () // returns querybuilder<t,id> custom complex query Requirements QueryBuilder ()

The above Deletebuilder, QueryBuilder, Updatebuilder are all integrated in Statementbuilder, so you can set the conditions by where () after Xxbuilder, as follows

Querybuilder<account, string> qb ==//  The Name field must is equal to "foo" wher E.eq (Account.name_field_name, "foo"//  and// The password FIELD must be equal to "_secret" where.eq (Account.password_field_name, "_secret"); Preparedquery<account, string> preparedquery = Qb.preparequery ();

It is only necessary to invoke different methods for different xxbuilder, such as delete (), query (), and update (). See the API documentation for more details.

Android Open Source ORM Framework Ormlite Use tutorial

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.