Getting Started with "Android notes" Ormlite

Source: Internet
Author: User
Tags try catch

PS: The purpose of writing this article is to try the new Markdown editor haha

Brief introduction

Ormlite provides a lightweight Object relational Mapping between Java classes and SQL databases. There is certainly more mature ORMs which provide this functionality including Hibernate and IBatis. However, the author wanted a simple yet powerful wrapper around the JDBC functions, and Hibernate and IBatis is Significa ntly more complicated with many dependencies.

Ormlite and Greendao are common ORM frameworks for Android platforms, each with an advantage, Ormlite wins in simplicity, but is based on annotation reflection, which is less than Greendao.
Ormlite Official website: http://ormlite.com/

Note: Ormlite can be used not only on Android platforms, but also in conjunction with JDBC

How to use

    • First you need to add a dependency of the Ormlite library into the Build.gradle:

dependencies {
Compile ' com.j256.ormlite:ormlite-core:4.48 '
Compile ' com.j256.ormlite:ormlite-android:4.48 '
}

    • Create a corresponding table in the bean mapping database

For example, I want to create a cell phone blacklist data table, the table is called black, table corresponding fields are as follows:

Number
ID name
Primary key, self-growth Name Number

If you use Sqliteopenhelper, you need to execute the SQL statement in OnCreate to create the table, but using ormlite only needs to create the following bean.

ImportCom.j256.ormlite.field.DatabaseField;Importcom.j256.ormlite.table.DatabaseTable;/** * Created by ROWANDJJ on 2015/5/26. * *@DatabaseTable(TableName ="BLACK") Public  class blackentity//Map to database is a table named black {    @DatabaseField(Generatedid =true) Public intId//Use Databasefield annotations to indicate that this is a field    @DatabaseField     PublicString name;@DatabaseField     PublicString number; Public blackentity(){} Public blackentity(string name, string number) { This. name = name; This. Number = number; }@Override     PublicStringtoString()    {return "blackentity{"+"Id="+ ID +", Name= '"+ name +' \ '+", number= '"+ number +' \ '+'} '; } PublicStringGetName()    {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetNumber()    {returnNumber } Public void Setnumber(String number) { This. Number = number; }}

More annotations, such as foreign keys, etc. see documentation

    • Inherit Ormlitesqliteopenhelper, and replicate related methods
      The most important are the OnCreate and Onupgrade methods.
ImportAndroid.content.Context;ImportAndroid.database.sqlite.SQLiteDatabase;ImportCom.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;ImportCom.j256.ormlite.dao.Dao;ImportCom.j256.ormlite.dao.RuntimeExceptionDao;ImportCom.j256.ormlite.support.ConnectionSource;ImportCom.j256.ormlite.table.TableUtils;ImportCom.taobao.easysafe.constants.DBConfig;ImportJava.sql.SQLException;/** * Created by ROWANDJJ on 2015/5/26. * * Public  class listdbhelper extends ormlitesqliteopenhelper{    /** blacklist * /    PrivateDao<blackentity, integer> Mblackdao;PrivateRuntimeexceptiondao<blackentity, integer> Mruntimeblackdao; Public Listdbhelper(Context context) {Super(Context, Dbconfig.bw_list/ * Database name * /,NULL,1); }@Override     Public void onCreate(Sqlitedatabase database, Connectionsource connectionsource) {Try{tableutils.createtable (Connectionsource, Blackentity.class); }Catch(SQLException e)        {E.printstacktrace (); }    }@Override     Public void Onupgrade(Sqlitedatabase database, Connectionsource Connectionsource,intOldversion,intNewVersion) {Try{tableutils.droptable (Connectionsource,blackentity.class);         OnCreate (database, Connectionsource); }Catch(Exception e)         {E.printstacktrace (); }    } PublicDao<blackentity, integer>Getblackdao()throwsSQLException {if(Mblackdao = =NULL) {Mblackdao = Getdao (Blackentity.class); }returnMblackdao; } PublicRuntimeexceptiondao<blackentity, integer>Getruntimeexceptionblackdao()    {if(Mruntimeblackdao = =NULL) {Mruntimeblackdao = Getruntimeexceptiondao (Blackentity.class); }returnMruntimeblackdao; }}

Ormlite provides the ability of the Tableutils class to perform the creation/destruction of tables for us.

    • Perform CRUD operations
      To perform a crud operation, you first get the DAO, the Getblackdao or Getruntimeexceptionblackdao method that calls Listdbhelper, The difference between the two methods is that Getruntimeexceptionblackdao does not require you to write a bunch of Try catch, which automatically throws an exception when a problem occurs.
      Now the question comes, how to get Listdbhelper instance? Direct new?? Of course not! A database connection is a rare resource and you should not create multiple instances. Ormlite provides the Openhelpermanager class to help us create an instance, invoking a static Gethelper:
ListDBHelper mDBHelper;privategetHelper(){     ifnull)     {         mDBHelper = OpenHelperManager.getHelper(this/*Context实例*/, ListDBHelper.class);     }     return mDBHelper;}

Listdbhelper Use the memory release, best practice is put into the activity of the OnDestroy:

@Override    protectedvoidonDestroy()    {        super.onDestroy();        ifnull)        {            OpenHelperManager.releaseHelper();            null;        }    }

With the Mdbhelper instance, we can get the DAO and call its Crud method:
Increase:

privatevoidaddToBlack(ContactInfo info){        ifnullnullnull)        {            new BlackEntity(info.getName(), info.getNumber());            getHelper().getRuntimeExceptionBlackDao().create(entity);        }}

Check:

privatequeryBlack()    {        return getHelper().getRuntimeExceptionBlackDao().queryForAll();    }

By deleting:
DAO provides a series of Delete methods, can refer to the use of the document, here is a more powerful deletebuilder, it can increase the where condition, and the API is the builder mode, nonstop dot point, completely stop ~haha, of course, Not only Deletebuilder, but also QueryBuilder, Updatebuilder, etc.

private void Removeblack (ContactInfo info) {int result =-1;if (info! = null) {Logger. D("TAG", info. GetName() +","+ Info. GetNumber());try {deletebuilder builder = Gethelper (). Getruntimeexceptionblackdao(). Deletebuilder();Builder. Where(). EQ("Name", info. GetName()). and(). EQ("Number", info. GetNumber());result = Builder. Delete();} catch (SQLException e) {E. Printstacktrace();}        }    }

Isn't it simple? Then hurry up and use it!

Ps:markdown's code is so ugly.

Getting Started with "Android notes" Ormlite

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.