Lessons learned from migrating to ORMLite

Dusan Bartos
AndroidPub

--

Over the last few months, we’ve been migrating our android app TS Warehouse from the classic DB approach (through the SQLiteOpenHelper) to ORMLite. I will try to summarize what we have learned, so you can be aware of what awaits you in the rough areas of RefactorLand. This will not be a tutorial for how to use ORM in an android app, but more like an ad flyer which will give you a hint or two about what to expect from migration on a production app.

ORMLite is an awesome library which will save you from typing yourself to death (eww boilerplate). But it’s not a magic tool which will be performing in every case.

Saved LOCs

This is not particularly a lesson, it’s just a nice fact. In most of the cases, ORMLite will save you hundreds of LOC. You just don’t have to write all of the cursor constructors for your classes anymore (well, most of the time as I will point out in the next sections).

Use batch operations

This one is pretty simple if you are at least a bit familiar with database transactions. Batch operation is a wrapper around lower level transaction, so if you are doing multiple DB manipulations in one step (i.e. saving an Order object with all of the OrderItem-s related to that object) you might want to use a batch operation. For those who are not familiar with transactions, it’s not just about a greater performance during the DB access, but it also allows you to do rollback.

Don’t remove all of the cursor code at all costs

I get it, it’s tempting to simply remove all of the cursor (POJO constructors) code once you started using ORMLite, but be careful, because in some situations (typically when you have some foreign objects or collections defined) it can be a lot faster to just use the classic implementation of creating an object from the cursor manually. In our app, it was the case of loading a lot of objects, which didn’t need much properties at load time, because they are lazily populated only when needed.

Optimize your DB schema with indices

I’m sure you do this, even if you have a little experience with DB design, so this is just a reminder. It can save you a serious amount of time during lookups. If you don’t know what DB index is, read about it here.

One DB index can cause the same performance gain as one week of business logic optimization.

Be careful with observing everything (ORMLite 5.0+ API)

This one is related to the update of ORMLite API, which introduced an implementation of pub-sub pattern in version 5.0. This is a powerful tool for both separating your code and using more reactive way of handling your DB manipulations. But this can also slow down your entire application if not used carefully. So just make sure you are observing only necessary tables (or better way — observe only a specific dataset with optimized query)

--

--