Pragmatic Programmer Issues

Spring jdbc namespace

One of the new feature of Spring Framework 3.0 is more namespaces. Today I want to write about jdbc namespace, which I’m using in last project.

The namespace is really simple, it has two main elements

  • initialize-database – which allow us to initialize database with scripts.
  • embedded-database – which allow us to start embedded database.

initialize-database

So we can use that xml tag to initialize our datasource with SQL scripts. There are some properties we should set:

  • data-source – which is javax.sql.DataSource bean reference. It will be used to connect and execute all the scripts.
  • enabled – if we should do anything so if we are enabled or not. (remember it can be property ${} or even spring EL), by default it is enabled.
  • ignore-failures – if we should ignore when statements end with errors.
    • NONE – do not ignore default value.
    • DROPS – we are ignoring failed DROP statements.
    • ALL – we ignore all failed statements.

And what is more important this tag has zero or more scripts tags. All this tags has location property which behave exactly the same as spring resources. In my application I create schema for production (I don’t use any ORM) and for tests I have the same schema with one more script (test data/fixtures – no more DbUnit problems 🙂 ).

It is soooo simple.

<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:/schema.sql">
</jdbc:script></jdbc:initialize-database>

embedded-database

The second tag, is really helpful when you want to use embedded database. Embedded database is helpful for things like storing configuration or other persistent application stuff.

It allow to simple start embedded database and make them visible as javax.sql.DataSource, ready to be injected to our JDBCTemplete objects. It has just two attributes:

  • id – which value becomes the bean name.
  • type – embedded database type

Actually those types are supported:


        
        
    

Under The Hood

All things starts at JdbcNamespaceHandler class, which register two parsers for elements. There is EmbeddedDatabaseBeanDefinitionParser for embedded-database element and InitializeDatabaseBeanDefinitionParser for initialize-database.

When everything is ok this elements build and configure two beans.

And that’s all.


Categories