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).

Solution:
Define your database connection in SqlMap.config as follows:

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

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

Then, manually configure the builder when initializing the mapper:

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

// Get connection string from web.config
ConnectionStringSettings dbConnStr =
ConfigurationManager.ConnectionStrings["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.