SSM Integration - spring Integration spring MVC and Mymatis

thinking

First, test whether Spring MVC and Mysteries are available, whether the environment is correct, and then use Spring integration.

  1. Build an integrated environment first
    2) Build Spring configuration environment
    3) Spring integrates Spring MVC framework
    4) Spring integrates Mybatis framework
    Required jar packages:
<!--AOP-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.9.4</version>
		</dependency>
		
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.4</version>
		</dependency>

<!--spring Dependency package-->
      <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>

 <!--  Spring MVC package -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

<!--unit testing-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.1.8.RELEASE</version>
    <scope>test</scope>
</dependency>
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

<!--affair-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.1.8.RELEASE</version>
</dependency>
<!--JDBC-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

<!--MySQL 5  drive -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

<!-- JSP and Servlet Relevant-->
 <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>

<!--EL Expression-->
<dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

<!--Journal-->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

<!--Mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<!--spring integration mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
</dependency>

<!-- Druid Connection pool-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
</dependency>

spring environment building

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

Open Annotation Scan:

<! - Open the annotation scan, hoping to scan the service and mapper layers, while the controller layer lets Spring MVC process - >
    <context:component-scan base-package="net.xikee">
		<! - Configuration does not sweep Controller annotations - >
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

The UserService Impl is handed over to Spring management, and the spring configuration is completed:
Test:

spring build completed

Spring MVC Environment Construction

1. Configure Dispatcher Servlet front-end control in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
        version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        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">
  <servlet>
    <!--Configuration of Front-end Controller:Server startup must be loaded and loaded at the same time springmvc.xml file-->
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--Configure initialization parameters and create them DispatcherServlet Object, load springmvc.xml configuration file-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--A Filter to Resolve Chinese Scrambling-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <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>
</web-app>

2. Create spring mv. 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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
	    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">
    <!--Open Annotation Scan, Scan Only Controller-->
    <context:component-scan base-package="net.xikee">
        <!--Only sweep Controller annotation-->
        <context:include-filter  type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--Configure View Parser Objects-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--Filtering static resources-->
    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    <!--open springMVC Annotation support-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

3. Write MVC Background User Controller
4. index.jsp and list.jsp


Finally click "Query" and jump to list.jsp. At this point, the Spring MVC environment is built.

spring Integration spring MVC


At this point, configure a listener in web.xml and set the path of the configuration file

<!--To configure Spring Monitor, loaded only by default WEB-INF Directory applicationContext.xml file-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--Setting the path of the configuration file-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

When the server starts, the application Context. XML file is loaded.

The Service layer can be accessed in the Controller layer, which indicates that Spring has successfully integrated Spring MVC.

mybatis framework building

1. Create mybatis-config.xml configuration file

<?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>
	<!-- Getting data sources -->
	<properties resource="jdbc.properties"></properties>
	<settings>
		<setting name="logImpl" value="STDOUT_LOGGING"/>
		<!-- Turn on lazy loading function -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
		<setting name="cacheEnabled" value="true"/>
	</settings>
	<environments default="default">
		<environment id="default">
			<transactionManager type="JDBC"></transactionManager>
			<!-- use mybatis Default database connection pool DBCP -->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
		<!-- Write (from configuration) SQL Sentence introduction -->
	<!--Introducing mapping configuration files-->
	<mappers>
		<!-- If placed in net.xikee.mapper Under the bag,<mapper resource="net/xikee/mapper/xxx.xml"/>-->
		<mapper resource="mapper/UserMapper.xml"/>
		<!--If annotated sql Statements written to methods can scan all of the packages mapper-->
		<!--<package name="net.xikee.mapper"/>-->
	</mappers>
</configuration>
  1. Create a database configuration file: jdbc.properties
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/web-demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
jdbc.driverClassName=com.mysql.jdbc.Driver

3. Create UserMapper.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="net.xikee.mapper.UserMapper">//Path of UserMapper.java interface
    <!-- <select id="queryAllUser" resultType="net.xikee.druid.pojo.User"> select
        * from user </select> -->

    <select id="queryAllUser" resultType="net.xikee.po.User">
        select * from t_user
    </select>
   </mapper>

4. Testing - - - Adding, deleting and modifying session.commit

mybatis framework is completed.

Spring integrates Mybatis

Think: How to give the proxy objects generated in Mybatis to spring container management and then inject them into service layer.
a) In the application Context. XML configuration file
Step 1: Configure connection pool;
Step 2: Configure SqlSessionFactory factory, IOC has factory object, you can get SqlSession object from container by spring, session.getMapper(UserMapper.class) obtains proxy object, with proxy, you can store it in IOC container;
Step 3: Configure the package where the mapper interface resides; spring knows which interface proxy objects need to be generated and stores them in the container.

 <!--spring integration Mybatis-->
    <!--Configure connection pool        data source-->
    <!-- Read under the class path properties Configuration in files -->
    <context:property-placeholder
            location="classpath:jdbc.properties" />
    <!-- data source -->
    <bean id="dataSource"
          class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="driverClassName"
                  value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- Configuration initialization size, minimum, maximum -->
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="10" />
        <!-- Configuration to get the connection waiting timeout time -->
        <property name="maxWait" value="10000" />
        <!-- How often is the configuration interval detected to detect idle connections that need to be closed in milliseconds? -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- Configure the minimum lifetime of a connection in the pool in milliseconds -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />
        <!-- It is recommended that the configuration be configured TRUE,Prevent fetched connections from being unavailable -->
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="false" />
        <!-- open PSCache,And specify on each connection PSCache Size -->
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize"
                  value="20" />
        <!-- Here we configure the submission mode, which defaults to TRUE,Configuration is not required -->
        <property name="defaultAutoCommit" value="true" />
        <!-- Verify that the connection is valid SQL,Different data configurations are different -->
        <property name="validationQuery" value="select 1 " />
        <property name="filters" value="stat" />
        <!-- <property name="proxyFilters"> <list> <ref bean="logFilter" /> </list>
            </property> -->
    </bean>
    <!--To configure SqlSessionFactory Factory Construction Through Connection Pool session Factory, so you need to pass the connection pool in-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--To configure mapper Package Mapping Scan Configuration Class for Interface Location -->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="net.xikee.mapper"></property>
    </bean>

At this point, spring integrates Mybatis configuration and the mybatis-config.xml file can be deleted.

b) Add the @Repository annotation to the mapper interface for Spring management

c) Inject UserMapper into the UserService class and operate the database by calling the corresponding method through the userMapper object.

After running, an error occurred: Invalid bound statement (not found): net.xikee.mapper.UserMapper.queryAllUser.

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): net.xikee.mapper.UserMapper.queryAllUser
	org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:227)
	org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:49)
	org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
	org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58)
	com.sun.proxy.$Proxy21.queryAllUser(Unknown Source)
	net.xikee.service.impl.UserServiceImpl.queryAllUser(UserServiceImpl.java:20)
	net.xikee.controller.UserController.querryAllUser(UserController.java:18)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	java.lang.reflect.Method.invoke(Method.java:498)
	org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
	org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
	org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
	org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
	org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)

Place the UserMapper.xml file and UserMapper.java in the same directory

Add in the pom.xml file

<build>
<!-- stay idea If this node is not added in, mybatis Placed in class package mapper Under bag mapper.xml Documents are missing. -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
</build>

So far, the integration has been successful.

Keywords: Spring Java Mybatis xml

Added by domineaux on Wed, 25 Sep 2019 06:20:42 +0300