Tuesday, 10 February 2009

Defining IBatis connection string in web.config

If you are using Ibatis you may want to move the connection string from the SqlMap.config file to the Web.config e.g. to enable its encryption (see previous post).

Define your database connection in SqlMap.config as follows:

<provider name="sqlServer2.0"/>
<dataSource name="DB" connectionString="${dbConnStr}"/>

Define connection string in Web.config:
<add name="dbConnStr" connectionString="some conn str"/>

Then, manually configure the builder when initializing the mapper:

// Create builder
DomSqlMapBuilder builder = new DomSqlMapBuilder();

// Get connection string from web.config
ConnectionStringSettings dbConnStr =

// Set dbConnStr property to
// populate in sqlmap.config
NameValueCollection properties = new NameValueCollection();
properties.Add("dbConnStr", dbConnStr.ConnectionString);
builder.Properties = properties;

// Create mapper
ISqlMapper mapper = builder.Configure("SqlMap.config");
IBatis framework is quite handy in use but the documentation is very poor. For more advanced questions you'll need to digg through fora and blogs. I've found this tip here.