Skip to main content

Integrating MyBatis 3.0.3 & Spring 3.0.5

Posted by mikevegap on December 23, 2010 at 9:25 PM PST

In this post I show how simple is to integrate mybatis and spring framework.

The requirements are:

 

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
class="line-number"> 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
class="line-number"> 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 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
...
class="line-number"> 9     http://www. class="xml-value">springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
class="line-number">10    
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
class="line-number">11    
http://www.spring class="xml-value">framework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" class="xml-tag">>
12     id="propertyConfigurer"
13           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
14           p:location="/WEB-INF/appdata/jdbc.properties" />
15     id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
16         name="driverClassName" value="${jdbc.driver}"/>
17         name="url" value="${jdbc.url}"/>
18         name="username" value="${jdbc.username}"/>
19         y name="password" value="${jdbc.password}"/>
20    
>
21
22     id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
23         name="dataSource" ref="dataSource"/>
24    
>
25     id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
26         name="dataSource" ref="dataSource" />
27           28    
>
29     id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
30         ref="sqlSessionFactory"/>
31    
>
32     id="workerDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
33         name="sqlSessionTemplate" ref="sqlSessionTemplate" />
34         name="mapperInterface" value="com.dacorp.fvm.dao.WorkerDao" />
35    
>
36 >
37

 The property configLocation points to the mybatis-config.xml  file:

 1 xml version="1.0" encoding="UTF-8"?>
2
3     PUBLIC "-//www.mybatis.org//DTD Config 3.0//EN"
4     "http://www.mybatis.org/dtd/mybatis-3-config.dtd">
5 >
6     >
7         name="cacheEnabled" value="false"/>
8    
>
9     >
10        
11         type="com.dacorp.fvm.dao.model.Worker" alias="Worker"/>
12         type="com.dacorp.fvm.request.mobile.UserRequest" alias="UserRequest"/>
13    
>
14     >
15         resource="com/dacorp/fvm/dao/queries/WorkerDao.xml" />
16    
>
17 ration>
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
3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4 "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
5 namespace="Worker">
6     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    
>
13
>
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
class="line-number"> 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.

Consider is the proper way to handle the transactions based on the application needs, 'cause using XML mapper files avoids the hardcoding of the SQL statements.

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
class="line-number"> 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
class="line-number"> 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 {
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

Comments

Hi Miguel. I suppose

Hi Miguel. I suppose ibatis-sqlmap-2.3.4.726 is not needed.

Integrating MyBatis 3.0.3 &

I'm using this against Spring 3.0.4 right now, and it works quite well, however, I strongly suggest that you don't use the @Select annotations. I find that mixing the SQL with the Java makes for a huge maintenance nightmare, especially if you have complex SQL (think queries that span many lines.)
Considering Java does not support multiline strings without using concatenation operators, it's simply too messy to mix SQL in code.
(Just my two cents, take it or leave it.)

I agree that using SQL annotations makes maintenance a hard ...

I agree that using SQL annotations makes maintenance a hard task. SQL annotations are good for demos or small projects. Excellent article that I was able to use as a template for my projects.

Gracias Miguel for sharing your knowledge.

Integrating MyBatis 3.0.3 &

I agree Rob, I simply post this as a quick help about these two frameworks ...
;)