[integration of spring MVC + Spring + mybatis integration program]

Because everyone has different ideas, I'll share my ideas here first
There are two types of persistent layer (DAO:DataBase Access Object persistent layer access object) for mybatis development.
First, the traditional way of developing persistence layer is that programmers need to develop persistence layer interface and persistence layer implementation class
The second one is that mybatis agent only needs the programmer to provide the interface of the persistence layer to develop the persistence layer. Since it can optimize the traditional development method,
The premise to save most of our programmers' work is that we need programmers to follow some development specifications.
I won't talk about the specification here. I forgot to review the third article of mybatis that I wrote
Since it is the integration framework, I will not use the original development persistence layer.





First, analyze the responsibilities of each framework:
Spring MVC: responsible for the presentation layer
Service interface: processing business
Mapper: persistence layer


spring is responsible for integrating layers
Manage mapper of persistence layer through Spring (equivalent to Dao interface)
Spring manages the service of the business layer, in which the mapper interface can be called
Spring controls transactions
Through the Spring management presentation layer handler, the service interface can be called in the handler



mapper, service and handler are all JavaBeans

Step 1: integrate dao layer
mybatis and spring are integrated to manage the mapper interface through spring.
Use mapper's scanner to automatically scan the mapper interface for registration in spring.

Step 2: integrate the service layer
Manage the service interface through spring.
Use configuration mode to configure the service interface in the spring configuration file.
Implement transaction control.


Step 3: integrate spring MVC
Because spring MVC is a module of spring, it does not need to be integrated.
Don't understand? It's OK to look at the picture again and relax.



 

This figure shows that all components run in the spring container.
What I want to say here is that students who are not familiar with spring have to work harder. I've covered most of the other two frameworks in the previous article.
Before the formal operation, I would like to introduce my development environment:
Eclipse Indigo-j2ee-64 bit, jdk-1.7.0_, Tomcat-7.0.65, Spring version 3.2, mybatis version 3.2.X
mysql-5.5.36-win32, database graphical operation tool: sqliog-10.0.0-0
Several important configuration files
Database script file content: direct copy execution commit





CREATE DATABASE /*!32312 IF NOT EXISTS*/`sms` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `sms`;

/*Table structure for table `t_user` */

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Unique identification',
  `username` varchar(32) DEFAULT NULL COMMENT 'User name',
  `age` int(11) DEFAULT NULL COMMENT 'User age',
  `gender` varchar(10) DEFAULT NULL COMMENT 'User gender',
  `birthday` varchar(64) DEFAULT NULL COMMENT 'User's birthday',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

log4j.properties deals with the database. This file is indispensable:

 

log4j.rootLogger=DEBUG, Console

#Console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  

log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG
There is also a db.properties file. Let me explain why to use a configuration file first, because the cost of compiling a configuration file is very small. Unlike a. java file, which needs to go through the steps of packaging, testing, publishing, etc., the configuration file can be directly used on site as long as the corresponding value is correct.

 

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root


Import jar package: I'll take a screenshot here

 

Overall engineering structure drawing

 

Important: profile introduction and configuration in the program
The first file: web.xml. The main responsibility of this file is to configure the program entry. In this file, you need to configure the spring container mentioned above because all components are running in the container. Then you need to configure restful url Filter, request parameter filter, spring context listener, front-end controller, etc
The contents of the document are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>ssm</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- Load spring container -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
    </context-param>
    <!-- Support Restful Style request Url -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Filter Chinese garbled code -->
    <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>
    <!-- spring Container monitor -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Configure front end controller -->
    <servlet>
        <servlet-name>ssm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Load front end controller profile context configuration location -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <!-- Start with server -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ssm</servlet-name>
                <!-- restful style url -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

The applicationContext-dao.xml file is mainly responsible for configuration: load db.properties, configure data source, configure SqlSessionFactoryBean, Mapper scanner
The contents are as follows:



<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        <!-- Load db.properties Content in file,db.properties In the file key There must be some special rules -->
        <context:property-placeholder location="classpath:db.properties"/>
        <!-- Configure data sources,Use dbcp Connection pool -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxActive" value="30"/>
            <property name="maxIdle" value="5"/>
        </bean>
        <!-- To configure SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- data source -->
            <property name="dataSource" ref="dataSource"/>
            <!-- Load mybatis Global profile for -->
            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        </bean>

        <!-- To configure Mapper Scanner -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- Scan package path,If you need to scan multiple packets, separate them with half angle commas -->
            <property name="basePackage" value="com.hanson.ssm.mapper"/>
            <!-- You can't use it here ref="sqlSessionFactory"The reason is that an error will be reported for the reference here because the configuration file is loaded above -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        </bean>
</beans>

 

applicationContext-service.xml this file is mainly responsible for scanning business layer components

The contents are as follows:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        <!-- Scan annotation@Repository Annotated service -->
        <context:component-scan base-package="com.hanson.ssm.service.impl.*"/>
</beans>

 

 

The applicationContext-transaction.xml configuration file is mainly responsible for transaction processing (this requires understanding of spring AOP concept, agent mode, reflection (must be able to) and other technologies)
Main contents of the document:



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

    <!-- Transaction manager pair mybatis Operational database transaction control, spring Use jdbc Transaction control class of -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- data source dataSource stay applicationContext-dao.xml Configured in -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- notice -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- Communication behavior -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- aop -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.hanson.ssm.service.impl.*.*(..))" />
    </aop:config>
</beans>

 

mvc-dispatcher-servlet.xml this configuration file is mainly responsible for loading annotation @ Controller class, opening annotation processor adapter, annotation processor mapper, view parser, etc
The contents of the document are as follows:



<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    <!-- Component scanners scan this layer groups scan processors -->
    <context:component-scan base-package="com.hanson.ssm.web.controller.*"></context:component-scan>
    <!-- Configure mappers and adapters for annotations and other configurations -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- Dealing with static resources -->
    <mvc:default-servlet-handler />
    <!-- Configure view resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

 

sqlMapConfig.xml this configuration file is mainly used to configure some settings of mybatis framework, such as opening the secondary cache, setting the alias of pojo, etc
The contents of the document are as follows:

 

<?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>
    <! -- global setting configuration, add as needed -- >
    <! -- configure alias -- >
    <typeAliases>
        <! -- batch scan set alias -- >
        <package name="com.hanson.ssm.pojo"/>
    </typeAliases>
    <! -- configure Mapper
        Note: since Spring is used to integrate the integration package of mybtais for mapper scanning, there is no need to configure it here
        Must follow: mapper.xml and mapper.java files have the same name and are in the same directory
        <mappers></mappers>
     -->
</configuration>

 

Summary: when these files are configured, java classes can write only the class name and annotation first, and the running error free description framework will be integrated successfully.

 

To: https://www.imooc.com/article/4833

Tags: Spring xml Mybatis log4j

Posted on Mon, 04 May 2020 04:36:55 -0400 by richardwarren