Spring+SpringMVC+Mybatis integration case

1. Build an integrated environment

Integration note: there are many ways to integrate ssm. We use xml configuration file + annotation
Integration ideas:
1. Set up a spring environment to run independently
2. Build = = springMVC = = environment, can run independently
3. Integrate the running environment of = = sping = = and = = springMVC = = and call the * * service * * business layer from the controller
4. Set up the * * Mybatis * * operating environment to query the database.
5. Integrate the running environment of spring and Mybatis. From the controller, you can call the service business layer, which can steal the dao persistence layer to add, delete, modify and query data.
Create database statement

 create database ssm;
 use ssm;
 create table account{
  id int primary key auto_increment  ;
  name varchar(30);
  money double;
}

ssm integer and pom.xml import coordinates

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.joyTop</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <!--version control-->
  <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <maven.compiler.source>1.8</maven.compiler.source>
      <maven.compiler.target>1.8</maven.compiler.target>
      <spring.version>5.0.2.RELEASE</spring.version>
      <slf4j.version>1.6.6</slf4j.version>
      <log4j.version>1.2.12</log4j.version>
      <mysql.version>5.1.6</mysql.version>
      <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
      <!---------- spring---------------------------------- -->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.8</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>compile</scope>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
      </dependency>
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.0</version>
          <scope>provided</scope>
      </dependency>
      <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
      <!-- log start -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${slf4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${slf4j.version}</version>
      </dependency> <!-- log end -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.0</version>
      </dependency>
      <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
          <type>jar</type>
          <scope>compile</scope>
      </dependency>
  </dependencies> 
</project>

2. Build and test the spring development environment including spring integration and Mybatis framework

Create a configuration file for applicationContext.xml

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

 <!--Enable annotation scanning,Hope to deal with service and dao,controller Unwanted spring Frame processing-->
 <context:component-scan base-package="com.joyTop">
     <!--Configure which annotations are not scanned-->
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>

 <!--To configure Spring Framework declarative transaction management-->
 <!--1.Configure transaction manager-->
 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource" ref="dataSource"></property>
 </bean>
 <!--2.Configure transaction notifications-->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find" read-only="true"/>
        <tx:method name="*" isolation="DEFAULT" />
    </tx:attributes>
 </tx:advice>
 <!--3.To configureAOPEnhance-->
 <aop:config>
     <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.joyTop.service.impl.AccountServiceinmp.*(..))"/>
 </aop:config>

 <!--Spring integration MyBatis frame=============================================-->
 <!--1.To configure c3p0 Connection pool -->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
     <property name="driverClass" value="com.mysql.jdbc.Driver"/>
     <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/>
     <property name="user" value="root"/>
     <property name="password" value="123.com"/>
 </bean>
 <!--2.To configure SqlSessionFactory factory-->
 <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource"></property>
 </bean>
 <!--3.To configure AccountDao Interface package-->
 <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.joyTop.dao"></property>
 </bean>
</beans>

service interface

public interface AccountService {
  //Query all account information
  public List<Account> findAll();
  //Save account information
  public void saveAccount(Account account);
}

The service interface implementation class provides service annotation and Autowired annotation

@Service("accountService")
public class AccountServiceinmp implements AccountService {

  @Autowired
  private AccountDao accountDao;

  @Override
  public List<Account> findAll() {
      System.out.println("Business layer findAll Executed....");
      return accountDao.findAll();
  }

  @Override
  public void saveAccount(Account account) {
      System.out.println("Business layer saveAccount Executed....");
      accountDao.saveAccount(account);
  }
}

service environment test

public class TestSpring {

  @Test
  public void run1(){
      //Load profile
      ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
      //Get objects
      AccountService as = (AccountService) ac.getBean("accountService");
      //Calling method
      as.findAll();
  }
}

The console output spring environment is completed
The business layer findAll executed....

2. Build and test the development environment of spring MVC, including spring integration and spring MVC framework

Create a configuration file for springMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=" http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd ">

 <!-- Annotations, package scanning -->
 <context:component-scan base-package="com.joyTop">
     <!--Configure scan only-->
     <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>
 <!--view resolver -->
 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
     <!-- File name prefix -->
     <property name="prefix" value="/WEB-INF/pages/" />
     <!-- Suffix of the file-->
     <property name="suffix" value=".jsp" />
  </bean>
 <!--Filter static resources-->
 <mvc:resources mapping="/css/**" location="/css/" />
 <mvc:resources mapping="/js/**" location="/js/" />
 <mvc:resources mapping="/images/**" location="/images/" />
 <!-- open SpringMVC Framework annotation support-->
 <mvc:annotation-driven  />
</beans>

Configuration of front-end web.xml, three components
1. controller: load the springMVC configuration file and create the DispatcherServlet when tomcat starts
2. Filter: depends on servlet container;
Based on function callback, almost all requests can be filtered;
The disadvantage is that a filter instance can only be called once during container initialization;
The purpose of using the filter is to do some filtering operations and obtain the data we want to obtain, such as: modify character code in the filter; modify some parameters of HttpServletRequest in the filter, including: filter vulgar text, dangerous characters, etc.
3. Listener: implements the server-side program of javax.servlet.ServletContextListener interface; starts with the start of web application; only initializes once; destroys with the stop of web application;
The main function is to do some initialization work, set some basic content, such as some parameters or fixed objects, etc. For example, spring MVC listener org.springframework.web.context.ContextLoaderListener implements spring MVC container loading, Bean object creation, DispatchServlet initialization, etc.

<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--1.Front end controller-->
<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--Initialization springMVC.xml configuration file-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springMVC.xml</param-value>
  </init-param>

  <!--Start the server and create the servlet-->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

<!--2.Solve post Filter for Chinese scrambling-->
<filter>
  <filter-name>characterEncodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <!--Set specific code set-->
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>characterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<!--3.To configure spring Monitor,Load only by default WEB-INF Directory applicationContext.xml configuration file-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--Set path to profile-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>

controller

<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--1.Front end controller-->
<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--Initialization springMVC.xml configuration file-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springMVC.xml</param-value>
  </init-param>

  <!--Start the server and create the servlet-->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

<!--2.Solve post Filter for Chinese scrambling-->
<filter>
  <filter-name>characterEncodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <!--Set specific code set-->
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>characterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<!--3.To configure spring Monitor,Load only by default WEB-INF Directory applicationContext.xml configuration file-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--Set path to profile-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>

Written by controller, calling service business layer

@Controller
@RequestMapping("/account")
public class AccountController {

  @Autowired
  private AccountService accountService;

  @RequestMapping("/findAll")
  public String findAll(Model model) {
      System.out.println("Presentation level: findAll......Implemented");
      List<Account> all = accountService.findAll();
      for (Account list : all) {
           System.out.println(list+"Presentation level: findAll......Implemented");
      }
      model.addAttribute("list",all);
      return "list";
  }

  @RequestMapping("/save")
  public String save(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception {
      System.out.println("Presentation level: save......Implemented");
      accountService.saveAccount(account);
      //Redirect to findAll page
      response.sendRedirect(request.getContextPath()+"/account/findAll");
      return "list";
  }
}

Front end request page and response page

<---------------Request page-index.jsp--------------->
<body>
 <a href="account/findAll">test</a>
 <form action="account/save" method="post">
     Full name:<input type="text" name="name"><br>
     Amount of money:<input type="text" name="money"><br>
     <input type="submit" value="Submission">
 </form>
</body>
<--------------Response page--list.jsp--------------->
<body>
<h1>Query all accounts</h1>
${list}
<h1>----------------------------------</h1>
<c:forEach items="${list}" var="account">
  ${account.name}
  ${account.money}
</c:forEach>

</body>

2. Build and test the development environment of Mybatis, including spring integration and Mybatis framework

 After the integration of Mybatis and spring, the SqlMapConfig.xml configuration file can not be used. The relevant configuration information will be integrated into applicationContext.xml

Create a configuration file for SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 <!--Configuration environment-->
 <environments default="mysql">
     <environment id="mysql">
         <transactionManager type="jdbc"></transactionManager>
         <dataSource type="POOLED">
             <property name="driver" value="com.mysql.jdbc.Driver"/>
             <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
             <property name="username" value="root"/>
             <property name="password" value="123.com"/>
         </dataSource>
     </environment>
 </environments>

 <!--Import mapping profile-->
 <mappers>
 <!--<mapper class="com.joyTop.dao.AccountDao" /> -->
     <!-- The files under this package are scanned -->
     <package name="com.joyTop.dao"/>
 </mappers>
</configuration>

Create Account entity class

//The custom encapsulation entity class implements serialization because the data is transferred
public class Account implements Serializable {
 private Integer id;
 private String name;
 private Double money;

 public Integer getId() {
     return id;
 }
 public Account setId(Integer id) {
     this.id = id;
     return this;
 }
public String getName() {
     return name;
 }
 public Account setName(String name) {
     this.name = name;
     return this;
 }
 public Double getMoney() {
     return money;
 }
 public Account setMoney(Double money) {
     this.money = money;
     return this;
 }
 @Override
 public String toString() {
     return "Account{" +
             "id=" + id +
             ", name='" + name + '\'' +
             ", money=" + money +
             '}';
 }
}

Create AccountDao persistence layer interface
The annotation used here does not use mapping file

//Account dao interface
@Repository  //dao level
public interface AccountDao {

 //Query all account information
 @Select("select * from account")
 public List<Account> findAll();

 //Save account information
 @Select("insert into account(name,money) values(#{name},#{money})")
 public void saveAccount(Account account);
}

Mybatis test
The annotation used here does not use mapping file

public class TestMyBatis {

 @Test//Query all
 public void run1() throws Exception {
     //Load profile
     InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
     //Create a sqlsessionfactory object
     SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
     SqlSessionFactory build = sqlSessionFactoryBuilder.build(in);
     //Create SqlSession object
     SqlSession sqlSession = build.openSession();
     //Get proxy object
     AccountDao dao = sqlSession.getMapper(AccountDao.class);
     List<Account> all = dao.findAll();
     for (Account list:all){
         System.out.println(list);
         System.out.println("--------------------------------");
     }
     //Shut off flow
     sqlSession.close();
     in.close();
 }

 @Test//Preservation
 public void run2() throws Exception {
     //Load profile
     InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
     //Create a sqlsessionfactory object
     SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
     SqlSessionFactory build = sqlSessionFactoryBuilder.build(in);
     //Create SqlSession object
     SqlSession sqlSession = build.openSession();
     //Get proxy object
     AccountDao dao = sqlSession.getMapper(AccountDao.class);
     Account account = new Account();
     account.setName("Lu Jun 4");
     account.setMoney(288000.0);
     dao.saveAccount(account);
     //Commit transaction (commit transaction except query)
     //sqlSession.commit();
     //Shut off flow
     sqlSession.close();
     in.close();
 }
}

Spring integrates MyBatis framework

  1. Objective: to configure the content in SqlMapConfig.xml configuration file to applicationContext.xml configuration file
  2. Add @ Repository annotation to the AccountDao interface
  3. Inject dao object into service for testing

summary

spring+springMVC+Mybatis integration is based on the spring framework. Spring and springMVC are integrated in web.xml (listener). Spring and Mybatis are integrated in the spring configuration file applicationContext.xml (c3p0 connection pool: c3p0, factory: sqlsessionfactorbean, MapperScannerConfigurer: folder scanner).

Published 22 original articles, won praise 0, visited 364
Private letter follow

Tags: Spring xml Mybatis MySQL

Posted on Tue, 17 Mar 2020 01:34:09 -0400 by Mr Mako