At work we mainly use Java as general purpose language, but we also pay attention to groovy. There are other scripting languages which are more mature and with a much better syntax, but for our purpose - scripting some Java applications and frameworks - it’s best suited. (You may read a nice article from Fowler about that.)
In one case we use IBatis in the persistence layer and startet to write services which use our SqlMapDaos in Groovy. So I thought about an generic DAO for SQL-Maps using groovy. I had implemented a DAO using Spring Aspects before, like in this article about a generic Hibernate DAO. But this requires at least to define an interface for the DAO. But because Groovy it uses dynamic typing, we can even drop that also.
I played around with different implementations and here’s an excerpt of a very simple one using only groovy. I shows very much the power of groovy over java, when using dynamic typing.
public class GroovyIBatisDao extends SqlMapClientDaoSupport {
def methodMapping = [
// findAll must be before find
“findAll” : “queryForList”,
“find” : “queryForObject”,
“insert” : “insert”,
“update” : “update”,
“delete” : “delete”
]
Object invokeMethod(String method, Object arguments) {
String useMethod = methodMapping.find{entry ->
method.startsWith(entry.key)
}.value
getSqlMapClientTemplate().“${useMethod}”(method, arguments[0])
}
}
Short, eh!? You can use it that way:
public class ExampleService {
def dao;
def doSomething(foo, bar) {
def thing = dao.findThingByFoo foo
def some = dao.findAllThingsByBar bar
thing.doItWith some
dao.updateThing thing
}
}
You only have to implement the three statements “findThingByFoo”, “findAllThingsByBar” and “updateThing” in the SQL Map and add a little configuration to your Spring context. You could even define your own “methodMapping” in the configuration.
As mentioned this is an trivial implementation. I added also added support for SQL Map namespaces. For performance reasons it’s good to implement missingMethod instead of invokeMethod and to create a new method for the DAO object. The main overhead will only be executed once per dynamic method. Also the mapping could be better - perhaps based on regular expressions - and we could support more SQL Map features. Perhaps more next week.
A week ago I posted about a GroovyIBatisDao. Here I like to tell you about a few details as I announced. First I added Support for SQL Map namespaces which are mandatory in our architecture. To avoid to much configuration I used a naming convention: Fo Kommentar (1)
Aufgenommen: Dez 22, 18:40