INTEGRATION OF MYBATIS WITH SPRING


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="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>StudentApplication-Mybatis</display-name>

 <servlet>
 <servlet-name>dispatcher</servlet-name>            
 <servlet-class>
    org.springframework.web.servlet.DispatcherServlet</servlet-class>
           <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
           </init-param>
   <load-on-startup>1</load-on-startup>
  </servlet>
 <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

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="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                         http://www.springframework.org/schema/beans/spring-beans.xsd
                         http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

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" />
</bean>

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/database.properties"/>
<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>
</bean>   
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"/>
</bean>
Include the bean for sqlSession

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

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"/>
</bean>  


The properties of MYSQL DB can be specified using extra properties file as shown below
Database Properties:
   database.driver=com.mysql.jdbc.Driver
   database.url=jdbc:mysql://localhost:3306/databaseName
   database.username=jhonsmith
   database.password= smith1234
   database.maxactiveconnections=3
  database.idleconnections=3
  database.initialSize=1

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

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 Student.java  and StudentMapper.java 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
StudentMapper.java

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  StudentMapper.java inside the package com.mybatis.mapper to support the database operations.

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

8. Create classes for Service Tier:
Create an interface class named StudentService.java 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 StudentServiceImpl.java
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;

@Service
public class StudentServiceImpl implements StudentService
     {
     @Autowired
     private StudentMapper studentMapper;
    @Autowired
   @Qualifier("studentSessionFactory")
   private SqlSessionFactoryBean studentSessionFactory;
//insert
   @Override
           public void insertStudent(Map guiMapMessage)
             {
                System.out.println(" data inserted...");
              studentMapper.insertDetails(guiMapMessage);
        }
}

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 StudentController.java inside the package
com.mouri.controller. This is where the routing logic of the application goes.

@Controller
@RequestMapping(value = { "/CourseService" })
public class StudentController {
@Autowired
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 = keysItr.next();
  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);
  }
  list.add(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);
  System.out.println(guiMapMessage.toString());
  Map searchMap = (Map) guiMapMessage.get("search");
  studentService.insertDetails(guiMapMessage);
     }
  catch (Exception e)
     {
 e.printStackTrace();
 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),
 PRIMARY KEY (`id`)
)

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,
MOURI Tech PVT LTD.
http://www.mouritech.com/


Comments