ORMLITE – Light Weight Object Relational Mapping – An Introduction

OVERVIEW ORM Lite provides a lightweight Object Relation Mapping between Java classes and SQL databases. ORM Lite supports JDBC connections to MySQL, Postgres, H2, SQLite, Derby, HSQLDB, and Microsoft SQL Server. ORM Lite also supports native database calls on Android OS. Using ORM Lite with Android Downloading ORMLITE To get started with ORM Lite, We need to download the ORM Lite jar files. These can be downloaded from ORM Lite release page Once we have downloaded ORM Lite, we will need to add it as an external library to our android project. Just Drop the jar file into your project’s libs/ subdirectory. We only need the ormlite-android-4.14.jar, not the ORM lite-core or any other packages. Getting Started with ORM Lite To get started with ORM lite we need to create our own database helper class which should extend the OrmLiteSqliteOpenHelper class. This class creates and upgrades the database when the application is installed and also provide the DAO(Data Access Object) classes used by other classes. The helper class must implement the methods

onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)

onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

onCreate creates the database when app is first installed while onUpgrade handles the upgrading of the database tables when we upgrade our app to a new version. The helper should be kept open across all activities in the app with the same SQLite database connection reused by all threads. If we open multiple connections to the same database, stale data and unexpected results may occur. It is recommended to use the OpenHelperManager to monitor the usage of the helper – it will create it on the first access, track each time a part of our code is using it, and then it will close the last time the helper is released. Once we define our database helper and are managing it correctly, We will use it in our Activity classes. An easy way to use the OpenHelperManager is to extend OrmLiteBaseActivity for each of your activity classes – there is also OrmLiteBaseListActivity, OrmLiteBaseService, and OrmLiteBaseTabActivity. These classes provide a helper protected field and a getHelper() method to access the database helper whenever it is needed and will automatically create the helper in the onCreate() method and release it in the onDestroy() method. Here is sample DatabaseHelper class http://ormlite.com/android/examples/DatabaseHelper.java Creating Table using ORM Lite There are a few things to notice when we use ORM Lite:
  1. We just annotate our class as a table and its members as fields and we’ re almost done with creating a table
  2. ORM Lite handles all of the basic data types without any explicit work on your part (integers, strings, floats, dates, and more).
  3. It is mandatory to have a no argument constructor in our class
In onCreate method of Databasehelper we create tables with help of TableUtils like
TableUtils.createTable(connectionSource, SimpleData.class);,
SimpleData here is name of table An example code to create Table in the onCreate callback:
 /**
 * This is called when the database is first created. Usually you should call createTable statements here to create
 * the tables that will store your data.
 */
 @Override
 public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
 try {
 TableUtils.createTable(connectionSource, SimpleData.class);
 } catch (SQLException e) {
 Log.e(DatabaseHelper.class.getName(), "Can't create table", e);
 throw new RuntimeException(e);
 }

Here is sample ORMLite table class

/**
 * A simple demonstration object we are creating and persisting to the database.
 */
 public class SimpleData {

// id is generated by the database and set on the object automagically
 @DatabaseField(generatedId = true)
 int id;
 @DatabaseField(index = true)
 String string;
 @DatabaseField
 long millis;
 @DatabaseField
 Date date;
 @DatabaseField
 boolean even;

SimpleData() {
 // needed by ormlite
 }

public SimpleData(long millis) {
 this.date = new Date(millis);
 this.string = (millis % 1000) + "ms";
 this.millis = millis;
 this.even = ((millis % 2) == 0);
 }

@Override
 public String toString() {
 StringBuilder sb = new StringBuilder();
 sb.append("id=").append(id);
 sb.append(", ").append("string=").append(string);
 sb.append(", ").append("millis=").append(millis);
 SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.S");
 sb.append(", ").append("date=").append(dateFormatter.format(date));
 sb.append(", ").append("even=").append(even);
 return sb.toString();
 }
 }

Hope that the blog gets you running on ORMLite, In the subsequent posts, we will explore more about ORMLite and how to use it to manipulate/retrieve data objects. References:
  1. ORMLite Sample table class (http://ormlite.com/android/examples/SimpleData.java)
  2. ORMLite example: (http://ormlite.com/android/examples/)