Android SQLite operation--Custom ORM Relationship Entity mapping class

Source: Internet
Author: User

Any Android application without the operation of the database, even the client program will have some specific data into the database, such as: User browsing records, Favorites list and so on, so the database operation is a very frequent operation, so the encapsulation of this part is very necessary, The Web side has a series of excellent frameworks such as Hibernate, although the Android application also has some open-source oom framework on git, but always feel that there is no need to introduce third-party things, so they encapsulate a database operation class, as long as the corresponding method to call this kind, Passing in the entity object to be saved or the updated entity object, the query is the same, as long as the incoming query condition and class, return the corresponding entity object, so as long as we do a package, we can directly use this class to manipulate the database, Instead of having to write complex SQL statements every time. Here's some of the code for my Encapsulation class:

Import com.micen.buyers.module.db.module;/********************************************************** * @ File name: Dbdatahelper.java * @ created on: 2014-2-10 02:41:51 * @ File Description: Database Operations Helper Class * @ Modify History: 2014-2-10 Create initial version ************************* /public Final class Dbdatahelper{private static dbdatahelper datahelper = null; Private DBHelper DBHelper = null;private static final String select = "Select";p rivate static final string from = "From ";p rivate static final string where =" where ";p rivate static final String order_by =" ORDER by ";p rivate Dbdatahelper () {dbhelper = Dbhelper.getinstance ();} public static Dbdatahelper getinstance () {if (Datahelper = = null) {Datahelper = new Dbdatahelper ();} return datahelper;} /** * Query database table based on criteria * @param tableName * @param showcolumns * @param selection * @param selectionargs * @param by * @par Am CLS * @return */public arraylist<module> Select (String tableName, String showcolumns, string selection, string SE Lectionargs,string OrderbY, class<?> cls) {synchronized (dbhelper) {arraylist<module> modulelist = new arraylist<module> (); Sqlitedatabase db = Null;try{db = Dbhelper.getreadabledatabase (); String sql = Select;sql + = Showcolumns! = null?  Showcolumns: "*"; sql + = from + tablename;if (selection! = NULL && Selectionargs! = null) {SQL + = WHERE + selection + "=" + Selectionargs;} if (~ = = null) {SQL + = order_by + by;} cursor cursor = db.rawquery (sql, NULL); Changetolist (cursor, modulelist, CLS);} catch (Exception e) {e.printstacktrace ();} Finally{dbhelper.closedatabase (db);} return modulelist;}} /** * Find Data table * * @param table * to manipulate tables * @param selection * Matching criteria, such as "Id>?and name <>?", do not need to be able to set Is null * @param Selectionargs * Corresponds to selection, the string inside will replace the "?" in the selection, * form the complete match condition, for example {"6", "Jack"} * @ param sort Parameters * @param moduleclass * To convert to the Model class classes, for example, to go to webpage into the webpage.class * @return Data Model collection, the collection is the object type Moduleclass */public Arraylist<mOdule> Select (Final string table, final string selection, final string[] selectionargs,final String, Final Clas S<?> moduleclass) {sqlitedatabase database = null; cursor cursor = NULL; arraylist<module> modulelist = new arraylist<module> (); synchronized (dbhelper) {try{database = Dbhelper.getreadabledatabase ();//query data cursor = database.query (table, NULL, selection, Selectionargs, NULL, NULL, , null);//Convert the result into a data model changetolist (cursor, modulelist, moduleclass);} catch (Exception e) {e.printstacktrace ();} Finally{dbhelper.closedatabase (database);} return modulelist;}} private void Changetolist (cursor cursor, list<module> modules, class<?> moduleclass) {//Remove all column names int count = CU Rsor.getcount (); Module Module;cursor.movetofirst (); synchronized (dbhelper) {try{//traversal cursor for (int i = 0; i < count; i++) {//Convert to Moduleclass An instance of the class module = changetomodule (cursor, moduleclass); Modules.add (module); Cursor.movetonext ();}} catch (SecurityException e) {//LOG.E (TAG, E + Fusioncode.empty_string);} catch (IllegalArgumentException e) {//LOG.E (TAG, E + fusioncode.empty_string);} catch (Illegalaccessexception e) {//LOG.E (TAG, E + fusioncode.empty_string);} catch (Instantiationexception e) {//LOG.E (TAG, E + fusioncode.empty_string);} catch (Nosuchfieldexception e) {System.out.println ("");} Finally{cursor.close ();}}} Private Module changetomodule (cursor cursor, class<?> moduleclass) throws Illegalaccessexception, Instantiationexception, SecurityException, nosuchfieldexception{synchronized (dbhelper) {//Remove all column names string[] ColumnNames = Cursor.getcolumnnames (); String filedvalue;int ColumnCount = columnnames.length; Field field;  Module module = (module) moduleclass.newinstance ();//Traversal with column for (int j = 0; J < ColumnCount; J + +) {//Find corresponding field according to column name field = Moduleclass.getfield (Columnnames[j]); filedvalue = Cursor.getstring (j); if (filedvalue! = null) {Field.set (module, Filedvalue.trim ());}} return module;}}          /** * Inserting data into a database * * @param table * Tables to manipulate * @param module *  Data model, the ID is set to self-increment, if not specified, is automatically generated, if specified to insert the specified ID, * But in the case that the data table already exists this ID will cause the insert to fail, it is recommended not to specify the ID * @return The line number of the inserted row, can be considered as ID */public long Insert (final String table, final Module module) {synchronized (dbhelper) {contentvalues values = moduletocontentvalues ( module); Return Dbhelper.insert (table, null, values);}} /** * Update data to the database * * @param table * tables to be manipulated * @param module * @return Update line number of lines, can be considered as ID */public long update (final St Ring table, final Module module) {synchronized (dbhelper) {contentvalues values = moduletocontentvalues (Module); return Dbhelper.update (table, values, dbhelper.id + "=?", new string[]{Module.id});} /** * Delete a data record * * @param table * to manipulate tables * @param module * Data model, the operation is deleted by ID, if the ID is null or incorrect is not deleted successfully * @ The number of rows affected by the return data table, 0 or 1 */public int Delete (final String table, final Module module) {synchronized (dbhelper) {return dbhelper . Delete (table, "Id=?", New string[]{Module.id});} /** * Delete Data * * @param table * Tables to manipulate * @param whereclause * Matching criteria, such as "id>? and name <>? ", the qualifying record will be deleted, * do not need to be set to NULL, so the contents of the entire table will be deleted * @param Whereargs * Corresponds to selection, the word inside The string will replace the "?" in the selection, * constitute the complete match condition, for example {"6", "Jack"} * @return the number of rows affected by the data table */public int Delete (final String table, fin Al String Whereclause, final string[] Whereargs) {synchronized (dbhelper) {return dbhelper.delete (table, Whereclause, Whereargs);}} /** * Convert module type to contentvalues * * @param module * SOURCE module * @return contentvalues * @author Shenghua.lin */PR  Ivate contentvalues moduletocontentvalues (final Module module) {contentvalues values = new Contentvalues ();  field[] fields = Module.getclass (). GetFields ();  String FieldName;  String Fieldvalue; int fieldvalueforint = -1;try{for (Field field:fields) {fieldName = Field.getname (); if (Field.get (module) instanceof Stri NG) {Fieldvalue = (String) field.get (module); if (fieldvalue! = null) {Values.put (FieldName, Fieldvalue.trim ());} Else{values.put (FieldName, "");}} else if (field.get (module) instanceofInteger) {fieldvalueforint = (integer) field.get (module), if (fieldvalueforint! =-1) {Values.put (FieldName, Fieldvalueforint);}}} catch (IllegalArgumentException e) {}catch (illegalaccessexception e) {}return values;}}

Idea: The crud operation of SQLite is actually the mutual transformation of entity class and Android Contentvalues, then we can achieve the mutual transformation between two kinds by reflection, we can realize ORM mapping. Avoid the cost of learning to introduce third-party libraries.


Android SQLite operation--Custom ORM Relationship Entity mapping class

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.