Android SQLite ORM

Source: Internet
Author: User

To the new year, recently more busy finishing the previous code.

The SQLite ORM Library, written in 14, was written in order to familiarize itself with the Android database operations as soon as possible. Then use this library to develop a few projects found with or relatively handy, so write a blog record it.

I understand the core idea of ORM is to use the object as a unit for the increase and deletion of the search.

App development naming a field is a hassle, especially when the page has a lot of controls, to take into account the interface developer naming style and the page to quickly identify the requirements, if the ORM re-request field names also consider the data table fields naming problem is too much trouble, So I used reflection to implement the correspondence between the model fields and the field of the data table.

public class Sqliteutil {private Sqlitedatabase db;    Private context context; /** * @param dbName * @param context * * Public sqliteutil (String dbName, Context context) {This.con        Text = context;    Open or CREATE DATABASE db = This.context.openOrCreateDatabase (dbName, context.mode_private, NULL);    }/** * The table statement, if the table does not exist the table is built * * * @param the table table structure, example tableName (field1 text primary key, Field2 integer) */ public void createtable (string table) {string cts = "CREATE table if not EXISTS" + table + ";";    /Build Table Statement Db.execsql (CTS);  }/** * Delete table * * @param table name */public void deletetable (string table) {String sql = "Drop        Table IF EXISTS "+ table;    Db.execsql (SQL);    /** * Execute SQL command * * @param SQL */public void Execsql (String sql) {db.execsql (SQL);   }/** * Add a new data */public <T> void Insert (String tableName, T data, class<t> clazz) {     String sql = "INSERT INTO" + TableName + "";        String fields = "(";        String value = "VALUES (";            For (Field F:clazz.getdeclaredfields ()) {f.setaccessible (true);                if (null! = F.getannotation (Sqlfield.class)) {Sqlfield ta = f.getannotation (sqlfield.class);                Fields + = Ta.field () + ",";  try {if (F.gettype (). Getsimplename (). Equals ("int")) {value + = F.getint (data) +                    ","; } else if (F.gettype (). Getsimplename (). Equals ("String")) {value + = "'" + f.get (data). ToString () +                    "‘,";                }} catch (Illegalaccessexception e) {e.printstacktrace ();        }}} fields = Fields.substring (0, Fields.length ()-1) + ")";        Value = value.substring (0, Value.length ()-1) + ")";        sql = SQL + fields + value; Staticmethod.debugemsg (SqL);    Db.execsql (SQL);         }/** * Modify data */public <T> void Update (String tableName, string where, T data, class<t> clazz) {        String sql = "UPDATE" + tableName + "SET";        String set = "";            For (Field F:clazz.getdeclaredfields ()) {f.setaccessible (true);                if (null! = F.getannotation (Sqlfield.class)) {Sqlfield ta = f.getannotation (sqlfield.class); try {if (F.gettype (). Getsimplename (). Equals ("int")) {set + = "" + Ta.field (                    ) + "=" + f.getint (data) + ",";                            } else if (F.gettype (). Getsimplename (). Equals ("String")) {if (F.get (data). toString ()! = null)                    Set + = "" + Ta.field () + "=" + f.get (data). ToString () + "',";                }} catch (Illegalaccessexception e) {e.printstacktrace (); }}} set = SEt.substring (0, Set.length ()-1);        sql = SQL + set + where;    Db.execsql (SQL);  }/** * Query method, return the corresponding array * * @param SQL * @param <T> generic object, you must provide a blank constructor * @return */Public         <T> list<t> query (String sql, class<t> clazz) {list<t> result = new arraylist<t> ();        Cursor c = db.rawquery (sql, NULL);                try {while (C.movetonext ()) {T temp = (t) class.forname (Clazz.getname ()). Newinstance ();                    For (Field F:clazz.getdeclaredfields ()) {f.setaccessible (true);                        if (null! = F.getannotation (Sqlfield.class)) {Sqlfield ta = f.getannotation (sqlfield.class); if (F.gettype (). Getsimplename (). Equals ("int")) {F.set (temp, C.getint (c.getc                        Olumnindex (Ta.field ()));                          } else if (F.gettype (). Getsimplename (). Equals ("String")) {  F.set (temp, c.getstring (C.getcolumnindex (Ta.field ())));            }}} result.add (temp);        }} catch (Exception e) {e.printstacktrace ();        } finally {c.close ();    } return result; }/** * * @param SQL query statement * @param fieldName the field name to return * @return return string contents */Public        list<string> query (String sql, String fieldName) {Cursor c = db.rawquery (sql, NULL);        list<string> result = new arraylist<string> ();        while (C.movetonext ()) {Result.add (c.getstring (C.getcolumnindex (FieldName)));        } c.close ();    return result; }}

There is no Delete method, the actual development of the deletion operation is a complex business, I have to encapsulate the SQL statement directly after the call Execsql (sqlString) to implement the deletion.

The query has 1 overloads because there are more business scenarios at development that only need to store and read a single field in a table, so it is cumbersome to implement a model for this field, so there are overloaded methods.

Reflection is used in the add-and-change, and SQL statements are not optimized. Because from the actual development point of view, to the application database of data magnitude, do not optimize the effect of the difference is not small, so you can rest assured edible.

Paste the annotation code.

@Target ({Elementtype.field}) @Retention (retentionpolicy.runtime) public @interface Sqlfield {    String FIELD ();}

Annotation Use Example

@SqlField (field = "field1") public    String key;    @SqlField (field = "Field2") public    String JSON;

For example, when executing a query, ORM extracts the value of field1 from the data table and assigns it to the key field. Remove the value of the Field2 field and assign the value to the JSON field.

Finally, I'll take a look at my experience, and I'll typically encapsulate the ORM again based on business requirements. For example, when caching, memory cache, sharedpreferences cache and SQLite cache, as well as file cache, are configured according to the business, where the SQLite cache can be implemented by the two-time encapsulation of this ORM.

Here is my SQLite cache implementation code

public class Sqlitecache {public static void clean (string key) {String sql = ' Delete from ' + Staticconstant.s        Qlcache + "where key= '" + key + "'";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); } public static void Save (Cachemodel cache) {String sql = ' Select key from ' + Staticconstant.sqlcache + ' wher        E key= ' "+ Cache.key +" ' "; if (StaticVariable.mSqLiteOper.query (SQL, "key"). Size () > 0) {StaticVariable.mSqLiteOper.update (staticconst Ant. SQLCache, "where key= '" + Cache.key + "'", Cache, CACHEMODEL.CLA        SS);                    } else {StaticVariable.mSqLiteOper.insert (Staticconstant.sqlcache, Cache,        Cachemodel.class); }} public static Cachemodel read (string key) {String sql = ' SELECT * from ' + Staticconstant.sqlcache + ' W        Here key= ' "+ key +" ' "; list<cachemodel> temp = StaticVariable.mSqLiteOper.query (sql, Cachemodel.class);        if (temp.size () > 0) return temp.get (0);    else return null; }}

SQLite cache classes are written according to the business, different apps have different business, the business is also changing at any time, so this class is for reference only.

Since it's all written to the cache, let me also file another example.

Push is an essential feature of most apps, and a well-experienced app that pushes to the end of the app is persistent until consumed by the user, such as a red dot unread reminder.

This requires caching of push messages, and when there are many types of push messages, cache management can be cumbersome, and a database must be used to manage the push cache.

  

public class Pushmsgcache {/** * first page read (task notification inside) */public static void Read1 (String uid) {String sql = "UPDATE" + Staticconstant.noticecache + "SET state = 2 WHERE state=1 and" + "type!= '" + staticconstant . dialog + "' and" + "type!=" + staticconstant. System notification + "' and" + "type!=" + staticconstant. Pin        Sell new User + "' and UserID = '" + uid + "'";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL);  }/** * Specific notification Level 1 read set */public static void Read1 (String uid, string msgtype) {String sql = "UPDATE" + Staticconstant.noticecache + "SET state = 2 WHERE" and "UserID = '" + uid + "' and type= '" +        Msgtype + "'";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); }/** * Level 2 Notification page read */public static void Read2 (String uid, string msgtype) {String sql = ' UPDATE ' + S Taticconstant.noticecache + "SET state = 3 WHERE" and "UserID = '" + uid + "' and TyPe= ' "+ Msgtype +" ' ";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); }/** * Details read */public static void Read3 (String uid, string msgtype) {String sql = "UPDATE" + Stati Cconstant.noticecache + "SET state = 4 WHERE" and "UserID = '" + uid + "' and type= '" + MSgt        ype + "'";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); }/** * List read */public static void Readwechatlist (String uid) {String sql = "UPDATE" + Staticconsta Nt. Noticecache + "SET state = 2 WHERE state=1 and" + "type= '" + staticconstant. Dialog + "' and UserID = '" + UI        D + "'";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); }/** * Message read */public static void Readwechat (String uid, String cid) {String sql = "UPDATE" + Stat                Icconstant.noticecache + "SET state = 3 WHERE" and "UserID = '" + uid + "' and targetid= '" +        CID + "' and type= '" + staticconstant. Dialogue + "'";STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL);  }/** * Follow up details reply read */public static void Readgjxqhf2 (String uid, String cid) {String sql = "UPDATE" + Staticconstant.noticecache + "SET state = 3 WHERE" and "UserID = '" + uid + "' and targetid= '        "+ CID +" ' and type= ' "+ staticconstant. Sales New user +" ' ";    STATICVARIABLE.MSQLITEOPER.EXECSQL (SQL); }/** * Push message Inbound * * @param JSON-pushed message object JSON */public static void Save (String json) {Gson        Gson = new Gson ();        Noticecachemodel model = new Noticecachemodel ();        Pushreceivermodel push = Gson.fromjson (JSON, pushreceivermodel.class);        Model.settype (Push.getmessagetype ());        Model.setmsg (Gson.tojson (push));        Model.settime (Staticmethod.getnowtimestamp () + "");        Model.settargetid (Push.getuid () + "");        if (Push.getadvid ()! = 0) {Model.setuserid (Push.getadvid () + ""); } else {Model.setuseriD (Push.getadvisorid () + "");        } model.setstate (1);    StaticVariable.mSqLiteOper.insert (Staticconstant.noticecache, model, noticecachemodel.class); /** * Read PUSH message * * @param pageName page name of data */public static list<pushreceivermodel> query (STR        ing pageName) {String sql = ""; Switch (pageName) {case "Xsgw_main"://Find all unread push information sql = "SELECT * from" + staticconstant.notic Ecache + "where userid= '" + Staticvariable.uid + "' and state=1 and" + "Ty                        Pe!= ' + staticconstant. Dialogue + "' and" + "type!= '" + staticconstant. Rob customers + "' and" +                        "type!=" + staticconstant. System notification + "' and" + "type!=" + staticconstant. Sales New user + "'" +                "ORDER BY time Desc";            Break Case ' xsgw_msgbox ': sql = ' select * from ' + Staticconstant.noticecache + ' where use 'Rid= ' + Staticvariable.uid + ' and state in ' ORDER by time Desc ';            Break                        Case "Xsjl_main": sql = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +                        Staticvariable.uid + "' and state=1 and" + "type!= '" + staticconstant. Dialogue + "' and" + "type!=" + staticconstant. Rob customers + "' and" + "type!= '" + staticconstant. System Notifications +                "' and" + "type!=" + staticconstant. Sales New user + "'" + "ORDER by time Desc";            Break                        Case "Xsjl_msgbox": sql = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +                Staticvariable.uid + "' and state in" Order by time Desc ";            Break                     Case "WeChat": sql = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +   Staticvariable.uid + "' and state ' and type= '" + staticconstant. Dialogue + "ORDER by time Desc";            Break                        Case "xsgw_main_activity": sql = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +                Staticvariable.uid + "' and state=1 Order by time Desc";            Break                        Case "Newnotice": sql = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +                Staticvariable.uid + "' and State in (type=) and '" + staticconstant. Manager notification + "'";            Break                        Case "SYSTEM"://unread system Notification SQL = "SELECT * from" + Staticconstant.noticecache + "where userid= '" +                Staticvariable.uid + "' and state ' and type= '" + staticconstant. System notification + "'";            Break        Default:return null; } list<noticecachemodel> temp = StaticVariable.mSqLiteOper.query (sql, NOTICECACHemodel.class);            if (temp.size () > 0) {gson Gson = new Gson ();            list<pushreceivermodel> result = new arraylist<> ();            for (Noticecachemodel item:temp) {Result.add (Gson.fromjson (Item.getmsg (), pushreceivermodel.class));        } return result;    } else return null; }}

For the processing of push messages, I use JSON to store in the database, using Gson to complete the serialization and deserialization of the data.

The core method in this class is save (message inbound) and query (unread message lookup), and the Readxxx series method is based on the message consumed by the different business, the role is to put the message as consumed.

Because I am currently developing a small team mode, 1-5 of people, the abstract demand for code, so when I write the class is more to consider the code easy to read and easy to modify, feel the level is too poor please light spray.

Android SQLite ORM

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.