Configuration and integration of Spring MVC and Mybatis

Posted by matt1019 on Sun, 19 May 2019 05:59:31 +0200

As we all know, with the progress of technology, SSM framework is very hot now, so for us, we need to understand the process of integration and configuration, so that we can quickly locate when Bug appears in the program. Here are some of the problems in SSM framework, if there are any inappropriate points, please correct them.

1. Configuration and description of Spring Mvc (based on XML configuration file)

First of all, we need to know that Spring MVC is a framework Web layer framework based on MVC, which solves the separation of front-end page and back-end code, and implements a method of request correspondence.

1. Import the necessary jar packages

To use Spring MVC, the first step is to import the necessary jar packages. The necessary jar packages for Spring MVC are:
4 spring core packages + 1 log packages + 2 spring MVC packages (web,webmvc) + 1 aop annotation packages.

2. Build a request on the front-end page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <a href="${pageContext.request.contextPath }/say.do">Click Send Request say</a>
</body>
</html>

3. Configuring Core Controller

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">


   <!-- Configure the core controller to intercept all requests -->
   <servlet>
     <servlet-name>dispatcherServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <!-- Specify the path of the configuration file -->
     <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:spring-mvc.xml</param-value>
     </init-param>
   </servlet>
   <servlet-mapping>
     <servlet-name>dispatcherServlet</servlet-name>
     <url-pattern>*.do</url-pattern>
   </servlet-mapping>

</web-app>


4. Create a Business Controller

package com.xkt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller //Component annotation
public class HelloController {
	
	@RequestMapping(value="/say")
	public String say(){
		System.out.println("HelloWorld!");
		return "/hello.jsp";
	}

}

5. Create Spring Profile

<?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:context="http://www.springframework.org/schema/context"
	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-4.3.xsd">

	<!-- Configuration Component Scanner -->
	<context:component-scan base-package="cn.gzsxt.controller"></context:component-scan>

</beans>

6. Create a return page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  //Hello world
</body>
</html>

Explain:
1. Spring MVC is thread insecure by default
2. After configuring the core controller, all requests can be intercepted in web.xml to implement a method corresponding to one request.
3. In the configuration file, we configure < init-parm > to specify a custom configuration file path. If you use the default path of the framework (placed under WEB-INF and named dispatcher Servlet-servlet.xml), you can not configure it.
4. Configuration < context: component-scan > is because we load class objects into containers through component annotations (@Controller). So it has to be configured.

2. Configuration of Mybatis (based on xml) and instructions

We need to know that Mybatis is a persistence framework. It can add, delete, modify and check the database, and use a small amount of code to realize the operation of the database, which can greatly improve the development efficiency.

1. Import the necessary jar packages
1 Mybatis package + 1 database driver package

2. Create DTD Specification Profile
Note: The configuration file of the Mybatis framework uses the DTD specification file. So it needs to be generated by DTD rule file. (Constraint files DTD and schema for xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
  
    <environments default="sms">
      <! - Any configuration file, parameters can be found in the framework code!! >
      <! -- Most frameworks, package names, configurations, abbreviations, builder s, and abbreviations for the classes in which the configuration file is interpreted - >
      <environment id="sms">
        <transactionManager type="JDBC"></transactionManager>
        <dataSource type="POOLED">
          Property corresponds to the set method - >.
          <property name="driver" value="org.gjt.mm.mysql.Driver"/>
          <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
          <property name="username" value="root"/>
          <property name="password" value="123456"/>
        </dataSource>
      </environment>
    </environments>
</configuration>

3. Create the help class MybatisUtils

package com.xkt.utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
	
	public static final SqlSessionFactory SSF=MybatisUtils.getSSF();
	private static final ThreadLocal<SqlSession> THREAD_LOCAL=new ThreadLocal<>();

	/**
	 * Get the Session Factory
	 * @return
	 */
	private  static SqlSessionFactory getSSF() {
		try {
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			return builder.build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * Get conversation
	 * @return
	 */
	public static SqlSession getSession(){
		if(THREAD_LOCAL.get()==null){
			SqlSession session = SSF.openSession();
			THREAD_LOCAL.set(session);
		}
		
		return THREAD_LOCAL.get();
	}
	
	/**
	 * Closing session
	 */
	public static void close(){
		if(THREAD_LOCAL.get()!=null){
			SqlSession session = THREAD_LOCAL.get();
			session.close();
			THREAD_LOCAL.remove();
		}
	}
	
	public static void main(String[] args) {
		System.out.println(MybatisUtils.getSession());
	}
	

}

4. Create entity classes

package com.xkt.pojo;

public class Student {
	private String stuId;//BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT'Student Number',
	private String stuName;//VARCHAR(50) NULL DEFAULT NULL COMMENT'Student Name',
	private String stuAge;//INT(11) NULL DEFAULT NULL COMMENT'Student Age',
	private String stuPassword;//VARCHAR(50) NULL DEFAULT NULL COMMENT'Password',
	public String getStuId() {
		return stuId;
	}
	public void setStuId(String stuId) {
		this.stuId = stuId;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public String getStuAge() {
		return stuAge;
	}
	public void setStuAge(String stuAge) {
		this.stuAge = stuAge;
	}
	public String getStuPassword() {
		return stuPassword;
	}
	public void setStuPassword(String stuPassword) {
		this.stuPassword = stuPassword;
	}
}


5. Create a mapping interface

packagecom.xkt.mapper;

import com.xkt.pojo.Student;

public interface StudentMapper {
	
	/**
	 * Insert students
	 * @param student
	 * @return
	 */
	int insert(Student student);

}

6. Create and load mapping files

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="com.xkt.mapper.StudentMapper">
   
   <insert id="insert">
    INSERT INTO tb_student	(stu_name, stu_age, stu_password) VALUES (#{stuName}, #{stuAge}, #{stuPassword})
   </insert>
</mapper>

7. Test insertion data

package com.xkt.test.mapper;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import  com.xkt.mapper.StudentMapper;
import  com.xkt.pojo.Student;
import  com.xkt.utils.MybatisUtils;

public class StudentMapperTest {
	
	@Test
	public void insert(){
		//Obtain the Operating Object
		SqlSession session = MybatisUtils.getSession();
		StudentMapper studentMapper = session.getMapper(StudentMapper.class);
		Student student=new Student();
		student.setStuName("Zhang San");
		int count = studentMapper.insert(student);
		System.out.println(count);
		session.commit();
		MybatisUtils.close();
		
	}

}

3. Spring MVC integrates Mybatis (based on xml)

Spring MVC integrates Mybatis by letting Mybatis abandon its own data source and use the data source provided by Spring. (Because we want Mybatis to use the transaction broker mechanism in the Spring framework, which relies on data sources in Spring JDBC)

1. Import the required jar package

2. The configuration file is configured in the following steps
Step 1: Configure the data source
Step 2: Get the Conversation Factory
Step 3: Get the operation object and inject it into the Spring container
Step 4: Configuring transaction agents

<?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:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


	<!-- 1.Configuring data sources -->
	<bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<!-- Four elements -->
		<property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/sms" />
		<property name="username" value="root" />
		<property name="password" value="1234" />

	</bean>

	<!-- 2.Configuring Session Factory -->
	<!-- By default: mybatis Do not support spring Data Source -->
	<!-- Question: So how can we make this happen? mybatis Support spring What about data sources? -->
	<!-- Answer: An integration package is needed. mybatis-spirng.jar
	SqlSessionFactoryBean:The function is to let Mybatis Can pass Spring Data source creates session factory
	 -->
	<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	   <!-- specify data source -->
	   <property name="dataSource" ref="dataSource"></property>
	   <!-- The path to load the mapping file -->
	   <property name="mapperLocations" value="classpath:com/xkt/mapper/xml/*Mapper.xml"></property>
	</bean>
	
	<!-- 3.Configure the scanner, create dynamic objects of the mapping interface, and inject them into the spring Inside the container -->
	<!-- By default: spring It does not support creating objects through interfaces!! and Mybatis It's about creating objects through interfaces.
	     Question: Spring Class creation must be implemented to inject into containers, and Mybatis It uses interfaces to create dynamic objects. Incompatible Spring Requirements. What shall I do?
	     Answer: The integration package provides a mapping interface scanner for creating objects through the mapping interface and injecting the created objects into the container.
	     -According to the description of two necessary conditions for scanners
	     1.Need a session factory
	     2.The path of the mapping interface must be specified
	 -->
	 
	 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	    <property name="basePackage" value="com.xkt.mapper"></property>
	    <!-- Specified Scan Annotation -->
	    <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"></property>
	 </bean>
	 
	
	<!-- 4.Configuring transaction agents, programmable transactions -->
	<!-- Be careful: Mybatis Yes spring jdbc Transaction Agent -->
	<!-- Creating Transaction Agent Objects -->
	<bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
	   <!-- specify data source -->
	    <property name="dataSource" ref="dataSource"></property>
	 </bean>
	 
	 <!-- Start Transaction Agent -->
	<tx:annotation-driven/>

</beans>

Topics: Spring Mybatis xml Session