[Android Notes] Getting started with ormlite and getting started with Android ormlite
Ps: the purpose of writing this article is to try a new markdown editor haha
Introduction
ORMLite provides a lightweight Object Relational Mapping between Java classes and SQL databases. there are 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 are significantly more complicated with independent dependencies.
Ormlite and GreenDao are common orm frameworks on the android platform. They have their own advantages. ormlite is more simple than greendao, but it is based on Annotation reflection, and the speed is less than GreenDao.
Ormlite Official Website: http://ormlite.com/
Note: ormlite can be used not only on the android platform, but also in combination with jdbc
How to Use
- First, you need to add the ormlite library dependency to build. gradle:
Dependencies {
Compile 'com. j256.ormlite: ormlite-core: 8080'
Compile 'com. j256.ormlite: ormlite-android: 8080'
}
- Create a table in the bean ing Database
For example, I want to create a data table named "black" on the mobile phone blacklist. The corresponding fields of the table are as follows:
Id |
Name |
Number |
Primary Key, auto-Increment |
Name |
Number |
If you use SqliteOpenHelper, You need to execute an SQL statement in onCreate to create a table, but you only need to create the following bean to use ormlite.
Import com. j256.ormlite. field. databaseField; import com. j256.ormlite. table. databaseTable;/*** Created by Rowandjj on 2015/5/26. * // @ DatabaseTable (tableName = "black") public class BlackEntity // ing to the database is a table named black {@ DatabaseField (generatedId = true) public int id; // The DatabaseField annotation indicates that this is a field @ DatabaseField public String name; @ DatabaseField public String number; public BlackEntity () {} public BlackEntity (String name, String number) {this. name = name; this. number = number ;}@ Override public String toString () {return "BlackEntity {" + "id =" + id + ", name = '"+ name +' \'' + ", number = '" + number +' \ ''+ '}';} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getNumber () {return number;} public void setNumber (String number) {this. number = number ;}}
For more annotations such as foreign keys, see the document.
- Inherit OrmliteSqliteOpenHelper and rewrite related methods
The main methods are onCreate and onUpgrade.
Import android. content. context; import android. database. sqlite. SQLiteDatabase; import com. j256.ormlite. android. apptools. ormLiteSqliteOpenHelper; import com. j256.ormlite. dao. dao; import com. j256.ormlite. dao. runtimeExceptionDao; import com. j256.ormlite. support. connectionSource; import com. j256.ormlite. table. tableUtils; import com. taobao. easysafe. constants. DBConfig; import java. SQL. SQLException;/*** Created by Rowandjj on 2015/5/26. */public class ListDBHelper extends OrmLiteSqliteOpenHelper {/** blacklist */private Dao <BlackEntity, Integer> mBlackDao; private RuntimeExceptionDao <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, int oldVersion, int newVersion) {try {TableUtils. dropTable (connectionSource, BlackEntity. class); onCreate (database, connectionSource);} catch (Exception e) {e. printStackTrace () ;}} public Dao <BlackEntity, Integer> getBlackDao () throws SQLException {if (mBlackDao = null) {mBlackDao = getDao (BlackEntity. class);} return mBlackDao;} public RuntimeExceptionDao <BlackEntity, Integer> getRuntimeExceptionBlackDao () {if (mRuntimeBlackDao = null) {mRuntimeBlackDao = getRuntimeExceptionDao (BlackEntity. class) ;}return mRuntimeBlackDao ;}}
Ormlite provides the TableUtils class to help us create/destroy tables.
- Perform the CRUD operation
To execute the CRUD operation, you must first obtain Dao, that is, call the getBlackDao or getRuntimeExceptionBlackDao methods of ListDBHelper. The difference between the two methods is that getRuntimeExceptionBlackDao does not need to write a bunch of try catch, when a problem occurs, the system automatically throws an exception.
Now, how can I get the ListDBHelper instance? New directly ?? Of course not! Database connection is a rare resource and should not be used to create multiple instances. Ormlite provides the OpenHelperManager class to help us create an instance and call static getHelper:
ListDBHelper mDBHelper; private ListDBHelper getHelper () {if (mDBHelper = null) {mDBHelper = OpenHelperManager. getHelper (this/* Context instance */, ListDBHelper. class);} return mDBHelper ;}
After using ListDBHelper, remember to release it. The best practice is to put it in onDestroy of the Activity:
@Override protected void onDestroy() { super.onDestroy(); if (mDBHelper != null) { OpenHelperManager.releaseHelper(); mDBHelper = null; } }
With the mDBHelper instance, we can get DAO and call its CRUD method:
Add:
private void addToBlack(ContactInfo info){ if (info != null && info.getName() != null && info.getNumber() != null) { BlackEntity entity = new BlackEntity(info.getName(), info.getNumber()); getHelper().getRuntimeExceptionBlackDao().create(entity); }}
Query:
private List<BlackEntity> queryBlack() { return getHelper().getRuntimeExceptionBlackDao().queryForAll(); }
Delete:
Dao provides a series of delete methods, which can be used in reference documents. Here we introduce a more powerful DeleteBuilder. It can add the where condition, and the api is a builder mode, without stopping the point, it cannot be stopped ~ Haha, of course, not only DeleteBuilder, but also QueryBuilder and UpdateBuilder.
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(); } } }
Is it easy? Use it now!
Ps: The markdown code is highlighted ugly.