Groovy DataSources for Railo

If you've ever wanted to do raw JDBC stuff in your ColdFusion applications, you probably know that you can get a javax.sql.DataSource via this code:

createObject("java", "coldfusion.server.ServiceFactory")

Unfortunately, this doesn't work on Railo, because the result isn't actually a javax.sql.DataSource, it just looks like one (see RAILO-43).  To put that another way, it's duck typed.

Fortunately, Groovy's "fake" interfaces make beating the typechecks fairly trivial (if kind of ugly):

<cfset = createObject("java", "coldfusion.server.ServiceFactory")
  .dataSourceService.getDatasource(my.dsn) />
  def rds = = {
  } as javax.sql.DataSource

The CFSET gets the "datasource" as normal, and then the little Groovy scriptlet simply wraps it with a closure and tells it to pretend to be a javax.sql.DataSource.  In this case we're assuming that the only method on DataSource that will be invoked is getConnection(), which is the usual case.  If you need to support other methods you'd need to go the Map-as-interface route.

Now we can use as a javax.sql.DataSource.  Yay!  Unfortunately, you have to use this sort of snippet everywhere you need a DataSource in your Railo apps, but hopefully that'll get fixed.

For more info on Groovy interfaces, the docs are at

Comments are closed.