In this post I show how simple is to integrate mybatis and spring framework.
The requirements are:
- Spring Framwork 3.0.5 + dependencies
- Mybatis 3.0.3 + dependencies
- aopalliance-1.0
- mybatis-spring-1.0.0-RC3
- ibatis-sqlmap-2.3.4.726
- lombok
- CoreJavaBeans1.0.1 + dependencies
First of all, let's define a model bean:
1 /*
2 * Worker.java
3 *
4 * Created on 21-dic-2010
5 *
6 * DACorp ? Software Consulting Services
7 * http://www.dacorpsoft.com
8 * (C) 2005-2010, Dacorp Project Management Committee (DPMC)
9 *
10 */
11
12 package com.dacorp.fvm.dao.model;
13
14 import lombok.Data;
15
16 /**
17 *
18 * @author Miguel Angel Vega Pabon
19 * @version 1.0, Developed with Netbeans 6.9
20 */
21 @Data
22 public class Worker {
23 private int id;
24 private String pin, firstName, lastName;
25 /** Default constructor */
26 public Worker(){
27 }
28 }
29
30
I simplify the coding using the Lombok api, @Data annotation encapsulates all the attributes from this class.
Mybatis needs to setup the DAO interfaces and behaviours.
1 /*
2 * WorkerDao.java
3 *
4 * Created on 21-dic-2010
5 *
6 * DACorp ? Software Consulting Services
7 * http://www.dacorpsoft.com
8 * (C) 2005-2010, Dacorp Project Management Committee (DPMC)
9 *
10 */
11 package com.dacorp.fvm.dao;
12
13 import com.dacorp.fvm.dao.model.Worker;
14 import com.dacorp.fvm.request.mobile.UserRequest;
15 import org.apache.ibatis.annotations.Select;
16
17 /**
18 * Define all allowed actions to handle Workers
19 * @author Miguel Angel Vega Pabon
20 * @version 1.0, Developed with Netbeans 6.9
21 */
22 public interface WorkerDao {
23 public Worker find(UserRequest request);
24 }
25
26
With the beans and the DAO defined we just need to combine them using the applicationContext.xml file of Spring Framework as follows:
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:aop="http://www.springframework.org/schema/aop"
5 xmlns:tx="http://www.springframework.org/schema/tx"
6 xmlns:p="http://www.springframework.org/schema/p"
7 xsi:schemaLocation="
8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
10 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
11 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
12 <bean id="propertyConfigurer"
13 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
14 p:location="/WEB-INF/appdata/jdbc.properties" />
15 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
16 <property name="driverClassName" value="${jdbc.driver}"/>
17 <property name="url" value="${jdbc.url}"/>
18 <property name="username" value="${jdbc.username}"/>
19 <property name="password" value="${jdbc.password}"/>
20 </bean>
21
22 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
23 <property name="dataSource" ref="dataSource"/>
24 </bean>
25 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
26 <property name="dataSource" ref="dataSource" />
27 <property name="configLocation" value="WEB-INF/config/mybatis-config.xml"/> 28 </bean>
29 <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
30 <constructor-arg ref="sqlSessionFactory"/>
31 </bean>
32 <bean id="workerDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
33 <property name="sqlSessionTemplate" ref="sqlSessionTemplate" />
34 <property name="mapperInterface" value="com.dacorp.fvm.dao.WorkerDao" />
35 </bean>
36 </beans>
37
The property configLocation points to the mybatis-config.xml file:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE configuration
3 PUBLIC "-//www.mybatis.org//DTD Config 3.0//EN"
4 "http://www.mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6 <settings>
7 <setting name="cacheEnabled" value="false"/>
8 </settings>
9 <typeAliases>
10 <!--Define a aliases for easy use of them inside the mapper-->
11 <typeAlias type="com.dacorp.fvm.dao.model.Worker" alias="Worker"/>
12 <typeAlias type="com.dacorp.fvm.request.mobile.UserRequest" alias="UserRequest"/>
13 </typeAliases>
14 <mappers>
15 <mapper resource="com/dacorp/fvm/dao/queries/WorkerDao.xml" />
16 </mappers>
17 </configuration>
18
mybatis-config.xml document derives to another XML document wich maps the SQL statements to the DAO interface method.
1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4 "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="Worker">
6 <select id="find" parameterType="UserRequest"
7 resultType="Worker">
8 select
9 wrk_id_pk as id,wrk_first_name as firstName,wrk_last_name as lastName,wrk_pin as pin
10 from
11 ${schema}.cla_workers where wrk_pin=#{pin}
12 </select>
13 </mapper>
14
15
Till here spring and mybatis works perfectly, but the last two files can be avoided just by taking advantage of some annotations and
capabilities provided in the applicationContext.xml document.
The line 27 from the applicationContext.xml can be ignored if we make the following changes in the WorkerDAO interface:
1 /*
2 * WorkerDao.java
3 *
4 * Created on 21-dic-2010
5 *
6 * DACorp ? Software Consulting Services
7 * http://www.dacorpsoft.com
8 * (C) 2005-2010, Dacorp Project Management Committee (DPMC)
9 *
10 */
11 package com.dacorp.fvm.dao;
12
13 import com.dacorp.fvm.dao.model.Worker;
14 import com.dacorp.fvm.request.mobile.UserRequest;
15 import org.apache.ibatis.annotations.Select;
16
17 /**
18 * Define all allowed actions to handle Workers
19 * @author Miguel Angel Vega Pabon
20 * @version 1.0, Developed with Netbeans 6.9
21 */
22 public interface WorkerDao {
23 //Using the following annotation, avoids the usage of mybatis-config.xml and derived mapper files
24 @Select("select "
25 + "wrk_id_pk as id,wrk_first_name as firstName,wrk_last_name as lastName,wrk_pin as pin "
26 + "from "
27 + "${schema}.cla_workers "
28 + "where "
29 + "wkr_pin=#{pin}")
30 public Worker find(UserRequest request);
31 }
32
33
Of course, ignoring the line of the property
makes useless the implementation of both mybatis-config.xml and WorkerDao.xml configuration files, that's because mybatis is able
to recognize the parameters and type of the objects to be returned from DAO interface, so there's no need to map them explicitly.
This means that they aren't necessary to make this example work, so they don't need to be in this example.
The important is that you must decide wheter is the most appropiate way to handle the transactions, 'cause using XML mapper files avoids the harcoding of the SQL statetements.
Let's look at the UserRequest class:
1 /*
2 * UserRequest.java
3 *
4 * Created on 21-dic-2010
5 *
6 * DACorp ? Software Consulting Services
7 * http://www.dacorpsoft.com
8 * (C) 2005-2010, Dacorp Project Management Committee (DPMC)
9 *
10 */
11
12 package com.dacorp.fvm.request.mobile;
13
14 import com.dacorp.fvm.request.NamedService;
15 import com.dacorp.fvm.request.Request;
16 import com.dacorp.fvm.response.Response;
17 import com.dacorp.fvm.response.mobile.UserResponse;
18 import java.io.IOException;
19 import javax.servlet.ServletException;
20 import javax.servlet.http.HttpServletRequest;
21 import lombok.Getter;
22 import org.cjb.xml.Xml;
23
24 /**
25 *
26 * @author Miguel Angel Vega Pabon
27 * @version 1.0, Developed with Netbeans 6.9
28 */
29 @NamedService(serviceName="find")
30 public class UserRequest extends Request{
31 @Getter
32 private String pin, schema;
33 /** Default constructor */
34 public UserRequest(){
35
36 }
37 @Override
38 public Response produceResponse(HttpServletRequest request) throws ServletException, IOException {
39 Xml xml = new Xml(request.getInputStream());
40 this.pin=xml.getChild("Pin").getTextTrim();
41 this.schema=xml.getChild("Schema").getTextTrim();
42 return new UserResponse(this);
43 }
44
45 }
46
47
Again, I'm encapsulating the attributes pin and schema using the Lombok annotation @Getter
An finally the usage can be implemented by the following class:
1 /*
2 * UserResponse.java
3 *
4 * Created on 21-dic-2010
5 *
6 * DACorp ? Software Consulting Services
7 * http://www.dacorpsoft.com
8 * (C) 2005-2010, Dacorp Project Management Committee (DPMC)
9 *
10 */
11 package com.dacorp.fvm.response.mobile;
12
13 import com.dacorp.fvm.dao.WorkerDao;
14 import com.dacorp.fvm.dao.model.Worker;
15 import com.dacorp.fvm.request.mobile.userRequest;
16 import com.dacorp.fvm.response.Response;
17 import java.io.IOException;
18 import java.io.PrintWriter;
19 import javax.servlet.ServletContext;
20 import javax.servlet.http.HttpServletResponse;
21 import org.cjb.xml.Xml;
22 import org.springframework.web.context.WebApplicationContext;
23 import org.springframework.web.context.support.WebApplicationContextUtils;
24
25 /**
26 *
27 * @author Miguel Angel Vega Pabon
28 * @version 1.0, Developed with Netbeans 6.9
29 */
30 public class UserResponse extends Response<UserRequest> {
31
32 /** Default constructor */
33 public UserResponse(UserRequest request) {
34 super(request);
35 }
36
37 @Override
38 public void writeResponse(ServletContext servletContext, HttpServletResponse response) throws IOException {
39 WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
40 WorkerDao partyDAO = (WorkerDao) wac.getBean("workerDao");
41 Worker w = partyDAO.find(request);
42 response.setContentType("text/xml");
43 Xml xml = new Xml("Response");
44 if (w == null) {
45 xml.addContent(xml.createElement("Exception", "Worker Not found"));
46 }
47 else{
48 xml.addContent(xml.createElement("Worker", w.getFirstName()+" "+w.getLastName()));
49 }
50 xml.write(response.getOutputStream());
51 }
52 }
53
54
Ok, the example above demonstrate how easy is to integrate SpringFramework 3 and Mybatis 3
There are some classes that aren't necessary to implement:
com.dacorp.fvm.request.NamedService
com.dacorp.fvm.request.Request
com.dacorp.fvm.response.Response
org.cjb.xml.Xml (this class is part of CoreJavaBeans API
I hope this post has been helpful for you...
Regards