Adding iBatis to OSGi application

Last blog post leaves us with working JDBC/Spring/OSGi. Now we want to sweet it with iBatis.

1. I used the same way as with ‘mysql-connector’ to add iBatis library jar (it’s the only one we need). So, again, I added it to JARs folder, then to bundle’s classpath and exported add com.ibatis packages.

2. Then what goes inside of iBatis folder:

File 1. Configuration file: ibatisconfig.xml:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE sqlMapConfig
PUBLIC “-//ibatis.apache.org//DTD SQL Map Config 2.0//EN”
http://ibatis.apache.org/dtd/sql-map-config-2.dtd”&gt;

<sqlMapConfig>

<settings useStatementNamespaces=”true”/>

<transactionManager type=”JDBC”>
<dataSource type=”SIMPLE”>
<property name=”JDBC.Driver” value=”com.mysql.jdbc.Driver”/>
<property name=”JDBC.ConnectionURL”
value=”jdbc:mysql://localhost/RELATE”/>
<property name=”JDBC.Username” value=”root”/>
<property name=”JDBC.Password” value=”123″/>
</dataSource>
</transactionManager>

<sqlMap url=”file:///home/ayarmula/projects/osgi/DAOLayer/ibatis/mapping/WebSite.xml”/>

</sqlMapConfig>

File 2. Mapping: WebSite.xml

<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE sqlMap
PUBLIC “-//ibatis.apache.org//DTD SQL Map 2.0//EN”
http://ibatis.apache.org/dtd/sql-map-2.dtd”&gt;
<sqlMap namespace=”WebSite”>

<resultMap class=”com.ak.domain.WebSite” id=”webSiteResultMap”>
<result property=”id” column=”ID”
javaType=”java.lang.Long” />
<result property=”displayName” column=”DISPLAY_NAME”
javaType=”java.lang.String” />

</resultMap>

<select id=”getWebsite” resultClass=”com.ak.domain.WebSite” resultMap=”webSiteResultMap”>
select ID as ID,
DISPLAY_NAME as displayName
from WEBSITE
where ID = #value#
</select>
</sqlMap>

3. So having this set there’s one thing left, use it from the application.

First of all, for Eclipse under Linux, resource ‘.’ folder is home/user. So include that in paths.

In SomeDAOImpl I tried using

Reader reader = Resources.getResourceAsReader(“projects/osgi/DAOLayer/ibatis/ibatisconfig.xml”);
SqlMapClient sqlMapper =
SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
Object ws =
sqlMapper.queryForObject(“WebSite.getWebsite”, new Integer(108));

but it kept telling that the resource was incorrect. I could get it working by:

Reader reader = new BufferedReader(new FileReader(new File(“projects/osgi/DAOLayer/ibatis/ibatisconfig.xml”)));

Also, there’s a trick in path to mapping file. As you can see about in ibatisconfig.xml, it only worked for me as <sqlMap url=”file:///home/ayarmula/projects/osgi/DAOLayer/ibatis/mapping/WebSite.xml”/>.

Leave a comment