Building Java Web Application Using MyBatis With Spring

This post will show how to create a Student application using MYSQL DB with MyBatis framework in a Spring environment. This is a simple application that aims to collect the input details from the user, to save the details in the MYSQL DB

MyBatis:  MyBatis (formerly known as iBatis) is a popular database access framework. MyBatis can be configured using XML configuration files. MyBatis Editor requires no configuration, adds no memory- or build-time overhead, and assumes all SQL Mapper configuration files in the same Eclipse project are related.

1. Create Java Web Application Project using Gradle Template
To begin with, in the IDE, create a Java Gradle project with the template of select a wizard as Gradle Project.
A sample snapshot as shown below



now click next, then give name to the project as StudentApplication-Mybatis.

And this will be the context-root of the application


now click on  finish.

In order to make project as Dynamic web project follow the below steps.

StudentApplication-Mybatis > properties > Project Facets >
click checkbox's  dynamic web Module, Java and JavaScript as shown below

The sample web application directory structure is shown below

2. web.xml

Add the contents of the web.xml to include the following:
  • A servlet and specify the location of the configuration file for the same. In this sample, a configuration file named springConfig.xml is created under WEB-INF/config folder in the project layout.
  • A servlet-mapping to map the servlet created in the above step that should be invoked when the client specifies the url matching the url pattern.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.1">


3. Create the Dispatcher-Servlet File

Create a dispatcher-servlet Bean Configuration file under the folder WEB-INF/config. If STS(Spring Tool Suite) is the IDE, go ahead and enable the context, mvc and tx namespaces. The DispatcherServlet.xml will be as shown below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
xmlns:xsi="" xmlns:p=""

After enabling the required namespaces, include the following (in between the <beans> and </beans> tags) to indicate that the application is annotation driven and base package for the context component scan.

<context:component-scan base-package="com.controllers,com.service,com.serviceImpl" />
<mvc:annotation-driven />

Include the bean InternalResourceViewResolver of Spring to locate the jsp files

<bean class="org.springframework.web.servlet.view. InternalResourceViewResolver">
<property name="prefix" value="/views/" />
<property name="suffix" value=".jsp" />

Include the bean for data source, where the properties of the MYSQL DB like url, username and password can be specified. Replace <$databse connection url> with the actual connection url for connecting to the MYSQL DB. Likewise, replace <$ database username> and <$database password> with the actual username and password values.

<context:property-placeholder location="WEB-INF/"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy- method="close">
<property name="driverClassName"><value>${database.driver}</value></property>
       <property name="url"><value>${database.url}</value></property>
       <property name="username"><value>${database.username}</value></property>
       <property name="password"><value>${database.password}</value></property>
<property name="maxActive"><value>${database.maxactiveconnections}</value></property>  <property name="maxIdle"><value>${database.idleconnections}</value></property>
<property name="initialSize"><value>${database.initialSize}</value></property>
Coming to the MyBatis specific configurations, include the bean for sqlSessionFactory which is the central configuration in a MyBatis application. This bean takes in three properties – dataSource (already configured above)  – typeAliasesPackage (location where the model classes of this application resides)  – mapperLocations (location where the mapper xml files for the model resides – this is not needed here as annotation based configurations are used instead)

<bean id="studentSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/mybatis-config.xml"/>
Include the bean for sqlSession

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
     <constructor-arg index="0" ref="sqlSessionFactory" />

Next and finally, include the bean for MapperScannerConfigurer

<bean id="StudentMapper"  class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface"     value="com.mybatis.mappers.StudentMapper"/>

The properties of MYSQL DB can be specified using extra properties file as shown below
Database Properties:
   database.password= smith1234

Mybatis Config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration SYSTEM "" PUBLIC "-// Config 3.0//EN">
<setting value="true" name="callSettersOnNulls"/>
<setting value="true" name="cacheEnabled"/>
<setting value="SESSION" name="localCacheScope"/>
<setting value="false" name="lazyLoadingEnabled"/>
<typeAlias alias="Student" type="com.mybatis.model.Student"/>
<mapper resource="com/ibatis/mapper/StudentMapper.xml"/>

4. Create JSP File for Student Application:

Create a folder named “jsp” under WEB-INF (This is where the jsp files will be created as indicated in the dispatcher-servlet.xml for the InternalResourceViewResolver bean).

Create a file index.jsp to include a form to get the input details like UserName and Password.
A snapshot of the index page is as follows


5. Create packages for Controller, Model, Service and Mappers:
Create packages each for the Spring Controller, Model and Service classes under the src/main/java folder. Also create a package for the MyBatis Mapper class under the same src/main/java folder.
A sample snapshot of the project after the package creation is as shown below:


6. Create classes for Model Tier:
Create a POJO class named  and inside the package com.mybatis.model to include the details of the Student model entity during login.
package com.mybatis.model;
public Student
     // no need of getters and setters
Instead of this just create an interface for the model

package com.mybatis.mapper;
import java.util.List;
import java.util.Map;

public interface StudentMapper
     void insertDetails(Map guiMapMessage);

7. MyBatis Mapper:
A Mapper in MyBatis framework is similar to the Repository tier in a Spring environment. Crude SQL queries takes its place here. Create an interface class named inside the package com.mybatis.mapper to support the database operations.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC '-// Mapper 3.0//EN'
<mapper namespace='com.mybatis.mappers.StudentMapper'>
  <insert id="insertStudent" parameterType="java.util.Map">
       INSERT INTO student (userName,Password) VALUES (#{usename},#{password});
where  userName, Password are the field names or column names in MYSQL DB

8. Create classes for Service Tier:
Create an interface class named inside the package com.mouri.service to support the service tier operations.
package com.mouri.service;
import java.util.List;
import java.util.Map;
public interface StudentService
   void insertDetails(Map guiMapMessage);
Create a service tier implementation class (a POJO indeed) named
inside the package com.mouri.serviceImpl. This is where the application logic goes –
either to save the student details into the database.

package com.mouri.serviceImpl;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.mybatis.mappers.StudentMapper;
import com.mouri.service.StudentService;

public class StudentServiceImpl implements StudentService
     private StudentMapper studentMapper;
   private SqlSessionFactoryBean studentSessionFactory;
           public void insertStudent(Map guiMapMessage)
                System.out.println(" data inserted...");

When using MyBatis with Spring, a mapper can be directly injected into the service tier.
This is probably the strongest point of the Spring integration of MyBatis.
This is the only tool that I am aware that lets to build the application with no imports to it.

9. Create class for Controller Tier:
Create a Controller tier POJO class named inside the package
com.mouri.controller. This is where the routing logic of the application goes.

@RequestMapping(value = { "/CourseService" })
public class StudentController {
private StudentService studentService;
public static Map<String, Object> jsonToMap(String jsonStr) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject(jsonStr);
if (null != jsonObject)
             retMap = toMap(jsonObject);
  return retMap;
//General method to convert JSON object to Map.
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
  Map<String, Object> map = new HashMap<String, Object>();
 Iterator<String> keysItr = object.keys();
 while (keysItr.hasNext()) {
  String key =;
  Object value = object.get(key);
    if (value instanceof JSONArray)
                       {    value = toList((JSONArray) value);
                  else if (value instanceof JSONObject)
        value = toMap((JSONObject) value);
map.put(key, value);
 return map;

//General method to convert JSONArray to Map.
public static List<Object> toList(JSONArray array) throws JSONException {
 List<Object> list = new ArrayList<Object>();
 for (int i = 0; i < array.length(); i++) {
  Object value = array.get(i);
  if (value instanceof JSONArray) {
   value = toList((JSONArray) value);
  } else if (value instanceof JSONObject) {
   value = toMap((JSONObject) value);
 return list;

@RequestMapping(value = { "/insertData" }, method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody Map insertEntry(@Valid @RequestBody String requestBody, HttpSession session) {
 Map returnMapMessage = new HashMap();
try {
  Map guiMapMessage = jsonToMap(requestBody);
  Map searchMap = (Map) guiMapMessage.get("search");
  catch (Exception e)
 returnMapMessage.put("result", "error");
 returnMapMessage.put("errortext","Internal Application Error. Contact Administrator" + e.getMessage());

10. Create the DB Schema in a MYSQL DB:
Connect to the MySQL DB which is to be used for this application and create a new DB Schema
named Karthik using the MySQL Workbench. This is necessary as the DB Schema name of Karthik is specified in the dataSource bean in dispatcher-servlet.xml
Once the Karthik DB Schema is created, create a table named student inside the DB Schema using the CREATE TABLE statement as follows:

CREATE TABLE `student` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `userName` varchar(255),
 `password` varchar(25),

11. Deploying the Application on Tomcat Server:
Once the above steps are complete and the project is successfully built, the Java web application is ready to deployed on the Tomcat Server 8.5.The Java web application can be deployed locally by right clicking on the project and choosing the “Run As->Run on Server” option.

The same can be deployed remotely on any native server that supports Tomcat by copying the WAR file (Right click on the project and choose Export as WAR File option) to /var/lib/tomcat7 folder (or appropriate tomcat directory) and restarting the tomcat server.

12. The Data in the Database:
After enrolling all the user details in the form like username and password, All the data
will be fetched into Karthik schema Database.

A Sample snapshot as shown below.

As you can observe that all the details will be fetched into the student table successfully.

Thanks & Regards,
Upender Reddy Dareddy,
Technical Trainee,