Hi Guys!,
Today we are learning about the OrmLite database in android.
In this post we will see the basics of OrmLite and its features and a little bit about its coding
In Android there are also several ways to do it, however the most advanced (in terms of flexibility and convenience) way to store structured data in Android is to use an SQLite relational database.
Probably everyone knows this, but still:
SQLite is basically a special file format and a set of APIs implemented in a library that ships with Android OS. Like most relational databases management systems SQLite API allows to manipulate data with SQL queries.
The programming model in which one has to manipulate data with plain SQL queries inside the application business logic is tedious, inconvenient and outdated. It should be forbidden to write spaghetti like code filled with SQL-queries in XXI century. Even if you are completely forced to write SQL queries in code and if you are a good programmer - you will find yourself writing some sort of framework that encapsulates common query routines and allows you to easier do similar operations on different data entities. What is more tedious, time-consuming and inconvenient - is dealing with SQLite API
The convenient programming model for me is:
- to be able to create/update objects in code and persist them by calling a method on a certain DB-manager object,
- to be able to fetch a set of objects with a certain predicate defined for one/several of the object's fields
This programming model is generally achieved with the help of any persistance/ORM framework such as Hibernate, however the latter is pretty heavy to be used in Android. There is an excellent alternative called ORMLite. As the name implies - it is a lightweight ORM framework, and it turns out to be well suited for Android.
OrmLite:
Object Relational Mapping Lite (ORM Lite) provides some lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. It supports a number of SQL databases using JDBC and also supports Sqlite with native calls to Android OS database APIs
Features:
Now we will jump a little bit about coding part,
Use Annotations to Mark Classes to be Persisted
To use the package you add the @DatabaseTable annotation to the top of each class and a @DatabaseField annotation to each of the fields in the class that are to be persisted to the database. For example:
@DatabaseTable(tableName = "accounts")
public class Account {
@DatabaseField(id = true)
private String name;
@DatabaseField(canBeNull = false)
private String password;
...
Account() {
// all persisted classes must define a no-arg constructor with at least package visibility
}
...
Sample Code Example
The ORMLite Android code includes base activity, service, and tab classes to help create and manage your database connections and DAOs. The following is a quick code example to give you a taste on how to use the package.
// you get the SQLiteOpenHelper from your Android Activity
ConnectionSource connectionSource =
new AndroidConnectionSource(sqliteOpenHelper);
// instantiate the DAO to handle Account with String id
Dao<Account,String> accountDao =
BaseDaoImpl.createDao(connectionSource, Account.class);
// if you need to create the 'accounts' table make this call
TableUtils.createTable(connectionSource, Account.class);
// create an instance of Account
String name = "Jim Smith";
Account account = new Account(name, "_secret");
// persist the account object to the database
// it should return 1 for the 1 row inserted
if (accountDao.create(account) != 1) {
throw new Exception("Failure adding account");
}
// retrieve the account
Account account2 = accountDao.queryForId(name);
// show its password
System.out.println("Account: " + account2.getPassword());
// close the connection source
connectionSource.close();
Today we are learning about the OrmLite database in android.
In this post we will see the basics of OrmLite and its features and a little bit about its coding
In Android there are also several ways to do it, however the most advanced (in terms of flexibility and convenience) way to store structured data in Android is to use an SQLite relational database.
Probably everyone knows this, but still:
SQLite is basically a special file format and a set of APIs implemented in a library that ships with Android OS. Like most relational databases management systems SQLite API allows to manipulate data with SQL queries.
The programming model in which one has to manipulate data with plain SQL queries inside the application business logic is tedious, inconvenient and outdated. It should be forbidden to write spaghetti like code filled with SQL-queries in XXI century. Even if you are completely forced to write SQL queries in code and if you are a good programmer - you will find yourself writing some sort of framework that encapsulates common query routines and allows you to easier do similar operations on different data entities. What is more tedious, time-consuming and inconvenient - is dealing with SQLite API
The convenient programming model for me is:
- to be able to create/update objects in code and persist them by calling a method on a certain DB-manager object,
- to be able to fetch a set of objects with a certain predicate defined for one/several of the object's fields
This programming model is generally achieved with the help of any persistance/ORM framework such as Hibernate, however the latter is pretty heavy to be used in Android. There is an excellent alternative called ORMLite. As the name implies - it is a lightweight ORM framework, and it turns out to be well suited for Android.
OrmLite:
Object Relational Mapping Lite (ORM Lite) provides some lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages. It supports a number of SQL databases using JDBC and also supports Sqlite with native calls to Android OS database APIs
Features:
- Setup your classes by simply adding Java annotations.
- Powerful abstract Database Access Object (DAO) classes to manage the object in the database
- Flexible QueryBuilder to easily construct simple and complex queries.
- Supports MySQL, Postgres, Microsoft SQL Server, H2, Derby, HSQLDB, and Sqlite and can be extended to additional databases relatively easily.
- Provisional support for DB2, Oracle, ODBC, and Netezza. Contact the author if your database type is not supported.
- Handles "compiled" SQL statements for repetitive query tasks.
- Supports "foreign" objects with the class field being the object but an id stored in the database table.
- Basic support for database transactions.
- Auto generates SQL to create and drop database tables.
Now we will jump a little bit about coding part,
Use Annotations to Mark Classes to be Persisted
To use the package you add the @DatabaseTable annotation to the top of each class and a @DatabaseField annotation to each of the fields in the class that are to be persisted to the database. For example:
@DatabaseTable(tableName = "accounts")
public class Account {
@DatabaseField(id = true)
private String name;
@DatabaseField(canBeNull = false)
private String password;
...
Account() {
// all persisted classes must define a no-arg constructor with at least package visibility
}
...
Sample Code Example
The ORMLite Android code includes base activity, service, and tab classes to help create and manage your database connections and DAOs. The following is a quick code example to give you a taste on how to use the package.
// you get the SQLiteOpenHelper from your Android Activity
ConnectionSource connectionSource =
new AndroidConnectionSource(sqliteOpenHelper);
// instantiate the DAO to handle Account with String id
Dao<Account,String> accountDao =
BaseDaoImpl.createDao(connectionSource, Account.class);
// if you need to create the 'accounts' table make this call
TableUtils.createTable(connectionSource, Account.class);
// create an instance of Account
String name = "Jim Smith";
Account account = new Account(name, "_secret");
// persist the account object to the database
// it should return 1 for the 1 row inserted
if (accountDao.create(account) != 1) {
throw new Exception("Failure adding account");
}
// retrieve the account
Account account2 = accountDao.queryForId(name);
// show its password
System.out.println("Account: " + account2.getPassword());
// close the connection source
connectionSource.close();