Saturday, March 19, 2011

Spring 3.1 with Cache and ORM technologies

Recently Spring Framework released Milestone 1 of version 3.1 (New features).  One of new key feature caught my eye is, support for cache using annotations. Now you can annotate your DAOs (or Repositories) with provided cache specific annotations and let spring take case of behind the scene bridge to cache provider.

To be fair, Cache using annotation is not new. It's been available as part of open source projects like http://code.google.com/p/ehcache-spring-annotations/. But now cache annotations, being part of core spring framework, it is going to be used more seriously and developed pro-actively.

Another major impact is, I am revisiting actual benefits of using ORM API for data access. As we all know, we have pretty much two ways to access database, either plain JDBC or ORM API like Hibernate. I am big fan of Hibernate, due to obvious reasons. And one of main reason is, adding cache capabilities by enabling 2nd level cache.  But in design sense, cache is more like cross-cutting requirement for a running system. Like any other cross-cutting concerns like Transactions, it makes more sense to use 'annotations' way.

Why back to JDBC now?
That's one decision, I recently made. I switched back to JDBC based DAO implementations instead of Hibernate backed DAOs.
  1. We all have experience of writing SQLs. And using Spring JDBC templates, it's very easy to implement methods.
  2. When we actually implementing DAOs, most of operations are not CRUD type. It's mostly join of multiple tables. Although HQL/JPQL can achieve can anything but it's another learning curve. 
  3. Personally, I don't want to add another layer API in whole technical stack. Hibernate (or any other ORM layer) is great and might have obvious benefits but it always have learning curve and yes, we spend time in debugging HQL or JPQL. 
  4. Major factor was 'cache' feature in Hibernate. Now Spring Framework provides cache annotations. It gives me more flexibility on what to cache and what not to. (even eviction policies are supported) 
  5. Plus spring cache annotation can be applied anywhere. Not just DAO, even remote webservices, or any method which is resource intensive. 
You can be setup and running by simple steps like upgrading spring dependency to 3.1.0-M1 (3.1.0.M1) and read this useful article at spring blog. 

Things which might need polishing
  • There seems to be incomplete code, how to generate key. (It's using just method name to generate key? )
  • Spring team is working on adding more providers (apart from ehcache). Support for providers like JBoss treecache will be nice. Specially in multi-cluster environment.
References:




No comments: