PS: The purpose of writing this article is to try the new Markdown editor haha
Simple 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 the ORM frameworks that are often used by Android platforms. Each has an advantage, ormlite wins in simplicity, but it is based on annotation reflection. Speed is inferior to 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
- The first thing you need to do is to join the Ormlite Library's dependencies into 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 would like to create a cell phone blacklist data table, the table is called black, table corresponding fields such as the following:
| ID |
name |
| Number
| Primary key, self-growth |
Name |
Number |
If you use Sqliteopenhelper, you need to run 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; }}
Many other annotations, such as foreign keys, etc. refer to the documentation
- Inherit Ormlitesqliteopenhelper. and replication-related methods
The most basic is 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 functionality of the Tableutils class to help us run the Create/Destroy table.
- Running CRUD Operations
To run a crud operation, you have to get the DAO first, that is to call Listdbhelper's Getblackdao or Getruntimeexceptionblackdao method, The difference between the two methods is that Getruntimeexceptionblackdao does not require you to write a bunch of try catch, and when it fails, it throws its own exception.
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, calling a static gethelper to:
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 document use, here is a more powerful deletebuilder, it can add the where condition, and the API is the builder mode, nonstop dot point, completely stop ~haha, of course, no, but Deletebuilder, and QueryBuilder, Updatebuilder and so on.
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 very easy? Then hurry up and use it!
Ps:markdown's code is so ugly.
Getting Started with "Android notes" Ormlite