MyBatis uses Spring-SpringMVC-MyBatis integration in -5-SSM-IDEA

table of Contents

0, official website

0.1 Integration of MyBatis-Spring-SpringMVC

0.2 SSM-Spring dependent jar package

0.3 The jar package that SSM-MyBatis depends on

0.4 SSM-MySQL driver dependent jar package

0.5 Bridge jar package required for the integration of SSM-MyBatis and Spring

0, create a javaweb project managed by Maven

1. Import the relevant jar package dependencies in the pom.xml file

1.1 Import Spring dependencies in the pom.xml file

1.2 Import SpringMVC and central controller ServletAPI dependency in the pom.xml file

1.3 Import MyBatis, MyBatis-Spring, MySQL database driver dependencies in the pom.xml file

1.4 Some other common components: log component, Apache component, Junit component, resources analysis, etc.

2. Configure Spring/SpringMVC/character encoding filter/load static resources in the web.xml file

3. Configure the integration of MyBatis and Spring in the spring.xml file

3.1 Configure the database configuration information that MyBatis needs to read in the jdbc.properties file

3.2 Configure the integration of MyBatis and Spring in the spring.xml file

4. Configure some auxiliary information of MyBatis in the myBatis.xml file, such as printing SQL, etc.

5. Configure startup annotation/scanning business/view parser, etc. in the springmvc.xml file

6、entity类-StudentEntity

7. Dao layer interface-StudentDao

8. The xml file corresponding to the dao layer interface-StudentMapper.xml

9. Service interface service: StudentService

10. Implementation of service interface service: StudentServiceImpl

11. Controller layer interface: StudentController

12. Unit testing

12.1 Unit test base class-BaseTest

12.2 Whether the unit test-service interface service is normal

12.3 Unit test-whether the Controller interface service is normal

12.3.1 Front-end jsp page

12.3.2 Front-end access test

0, official website

(1) MyBatis official website: https://mybatis.org/mybatis-3/zh/index.html

(2) The official website of the MyBatis top-level catalog: https://github.com/mybatis?page=1

(3) Integration of MyBatis-Spring-official website GitHub-jar package download: https://github.com/mybatishttps://github.com/mybatis/spring/releases

(4) Integration of MyBatis-Spring-Study of official website information: http://mybatis.org/spring/zh/index.html

(5) Spring framework:

(6) SpringMVC framework:

(7) MyBatis framework:

(8) Spring-SpringMVC-MyBatis integration quick start : https://www.bilibili.com/video/BV1hE411F77L?from=search&seid=6846725922532139162

(9) How to use idea to create a Javaweb project managed by Maven : https://blog.csdn.net/cmm0401/article/details/111773134

0.1 Integration of MyBatis-Spring-SpringMVC

0.2 SSM-Spring dependent jar package

0.3 The jar package that SSM-MyBatis depends on

0.4 SSM-MySQL driver dependent jar package

0.5 Bridge jar package required for the integration of SSM-MyBatis and Spring

0, create a javaweb project managed by Maven

For details, please refer to : https://blog.csdn.net/cmm0401/article/details/111773134

1. Import the relevant jar package dependencies in the pom.xml file

[Integrated Spring Framework + Integrated Spring MVC Framework + Integrated MyBatis Framework]

1.1 Import Spring dependencies in the pom.xml file

1.2 Import SpringMVC and central controller ServletAPI dependency in the pom.xml file

1.3 Import MyBatis, MyBatis-Spring, MySQL database driver dependencies in the pom.xml file

1.4 Some other common components: log component, Apache component, Junit component, resources analysis, etc.

<?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.wind</groupId>
    <artifactId>ssm-wind</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

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

    <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.2.5.RELEASE</spring.version>
        <javax.servlet.version>4.0.0-b07</javax.servlet.version>
        <jstl.version>1.2</jstl.version>
        <mysql.connector.java.version>8.0.13</mysql.connector.java.version>
        <druid.version>1.1.18</druid.version>
        <mybatis.version>3.4.6</mybatis.version>
        <mybatis.spring.version>2.0.3</mybatis.spring.version>
        <junit.version>4.13</junit.version>
    </properties>

    <dependencies>

        <!--集成Spring框架+集成SpringMVC框架+集成MyBatis框架-->

        <!--集成Spring框架开始-->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</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-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--集成Spring框架结束-->

        <!--集成SpringMVC框架开始-->

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

        <!--servletAPI:Spring不会主动帮我们导入servletAPI,需要自己导入依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${javax.servlet.version}</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>

        <!--集成SpringMVC框架结束-->

        <!--集成MyBatis框架开始-->

        <!--Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

        <!--MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.java.version}</version>
        </dependency>

        <!--(1)原始的JDBC数据源-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--(2)阿里巴巴的数据源,而不是JDBC的数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!--(3)C3P0数据源:数据库连接池-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!--集成MyBatis框架结束-->

        <!--集成MyBatis整合Spring开始-->

        <!--SpringMVC和Spring不需要整合,因为SpringMVC只是一个Spring的部分-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

        <!--集成MyBatis整合Spring结束-->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>


        <!--项目基础组件开始-->

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.69</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

        <!--引入日志框架log4j-->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>

        <!--项目基础组件结束-->

    </dependencies>

    <build>
        <finalName>ssm-wind</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!--手动设置jdk编译版本-->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>${maven.compiler.source}</source>
                        <target>${maven.compiler.target}</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>

        <!--
           maven默认扫描src/main/java中的文件而不理会src/main/resources中的xml文件,
           所以后来添加了resource节点,这样就将src/main/resources中的xml文件改变maven默认的扫描策略,防止造成src/main/resources下的配置文件打包丢失.
       -->
        <!--编译之后的文件中少了mapper.xml,这个和maven有关,maven编译src/java代码的时候,默认只会对java文件进行编译然后放在target/classes目录,需要在pom.xml中加入下面配置-->
        <!--如果不添加此节点,mapper.xml文件、config.properties文件、config.spring文件都不会被加载到target的classes中去,也就不能被使用,也就会报错-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

    </build>
</project>

2. Configure Spring/SpringMVC/character encoding filter/load static resources in the web.xml file

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

    <display-name>Archetype Created Web Application</display-name>

    <!--1.加载Spring配置文件,即启动Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <!--2.防止Spring内存溢出监听器-->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!--3.加载spring容器监听器-->
    <!--Spring容器启动时,会被这个监听器监听到,然后它会读取contextConfigLocation所配置的xml文件,
    之后再去创建xml文件中的bean实例,最后放进Spring容器中去管理-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--4.加载SpringMVC配置文件,创建SpringMVC中央控制器-->
    <servlet>
        <servlet-name>MVC-DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载SpringMVC时需要的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--标记Spring容器在启动的时候就加载这个Servlet中央控制器-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>MVC-DispatcherServlet</servlet-name>
        <!--为中央控制器配置拦截路径:默认拦截所有的HTTP请求-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--5.使用自动的过滤器来解决工程编码时出现乱码的问题-->
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--6.配置加载静态资源的功能
    (MVC-DispatcherServlet会拦截所有资源,所以对这些静态资源单独拿出来由默认的servlet去处理)-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.png</url-pattern>
    </servlet-mapping>

</web-app>

3. Configure the integration of MyBatis and Spring in the spring.xml file

3.1 Configure the database configuration information that MyBatis needs to read in the jdbc.properties file

##数据库驱动
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
##MySQL连接信息
jdbc.url=jdbc:mysql://127.0.0.1:3306/RUNOOB?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
##用户名
jdbc.username=root
##密码
jdbc.password=root

3.2 Configure the integration of MyBatis and Spring in the spring.xml file

<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">


    <context:component-scan base-package="com.wind.*"/>

    <!--Mybatis和Spring的整合:由Spring来管理MyBatis组件-->

    <!--1.获取数据源dataSource:常见的数据源:c3p0,dbcp,druid等-->
    <!--1.1 获取数据库配置文件-->
    <context:property-placeholder location="classpath:properties/jdbc.properties"/>
    <!--1.2 根据数据库配置文件获取数据源,并命名为唯一的beanID=dataSource-->
    <!--比如:c3p0数据库连接池:<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">-->
    <!--比如:阿里巴巴提供的的Druid数据库连接池:用来创建一个数据库连接池类型的数据源,可以实现数据库连接共用,减少连接重复创建销毁的时间-->
    <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}"/>
        <!--配置数据库连接池的初始化大小、最小、最大-->
        <property name="initialSize" value="5"/>
        <property name="minIdle" value="5"/>
        <property name="maxActive" value="20"/>
        <!--配置获取连接等待超时的时间,单位是毫秒-->
        <property name="maxWait" value="10000"/>
        <!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒-->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!--配置一个连接在池中最小生存的时间,单位是毫秒-->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
    </bean>


    <!--2.创建sqlSessionFactory对象-->
    <!--MyBatis处理mysql数据的时候,需要一个SqlSession对象,这个对象怎么来呢?是通过sqlSessionFactory工厂来创建的-->
    <bean id="sqlSessionFactory" name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入属性:数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--注入属性:指定MyBatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <!--注入属性:指定Mybatis映射文件,也即DAO层接口对应的xml文件,自动扫描xxxMapper.xml文件,*.xml会匹配所有xml文件-->
        <property name="mapperLocations" value="classpath:mappers/*.xml"/>
    </bean>


    <!--3.配置Spring需要扫描的DAO层接口-->
    <!--扫描指定包中所有的DAO层接口,把这些接口作为Mapper接口进行注册到Spring中,
    扫描到的类型只要是接口就会被注册,所以指定的包中通常只放Mapper接口,避免存放一些不相干的类或者接口-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wind.dao"/>
    </bean>

</beans>

4. Configure some auxiliary information of MyBatis in the myBatis.xml file, such as printing SQL, etc.

<?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>

    <!--使用mybatis操作数据库,那么当然需要配置数据库相关信息,这个需要在mybatis的全局配置文件中进行配置。
    mybatis提供一个全局配置的xml文件,可以在这个配置文件中对mybatis进行配置,如事务的支持,数据源的配置等等,
    这个属于配置文件,我们一般放在main/resources中,也就是此文件-->

    <!--在mybatis中一般我们将一个表的所有sql操作写在一个mapper.xml中,一般命名为XXXMapper.xml格式。-->
    <!--(1)一般情况下,我们会创建一个和Mapper.xml中namespace同名的Mapper接口,Mapper接口会和Mapper.xml文件进行绑定;-->
    <!--(2)mybatis加载mapper.xml的时候,会去查找namespace对应的Mapper接口,然后进行注册,我们可以通过Mapper接口的方式去访问Mapper.xml中的具体操作;-->
    <!--(3)Mapper.xml和Mapper接口配合的方式是比较常见的做法,也是强烈建议大家使用的。-->

    <!--另:很多的配置信息直接写在了spring.xml配置文件中了,所以这里基本上没有内容。-->

    <settings>
        <!-- 打印SQL-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名的用法:别名使用时是不区分大小写的:org.apache.ibatis.type.TypeAliasRegistry-->
    <!--使用别名之前需要先在mybatis中注册别名,我们先说通过mybatis全局配置文件中注册别名,通过mybatis配置文件注册别名有3种方式。-->
    <!--方式1:使用typeAlias元素进行注册-->
    <!--方式2:通过package元素批量注册-->
    <!--方式3:package结合@Alias批量注册并指定别名-->
    <typeAliases>
        <!-- 指定包名,MyBatis会在包名下搜JavaBean并将别名注册到mybatis中:实体类的别名,默认是首字母小写的类名作为对象名-->
        <package name="com.wind.entity"/>
    </typeAliases>

</configuration>

5. Configure startup annotation/scanning business/view parser, etc. in the springmvc.xml file

<?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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


    <!--启动注解驱动-->
    <mvc:annotation-driven>
        <!-- 处理请求返回json字符串的中文乱码问题-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--扫描业务代码-->
    <context:component-scan base-package="com.wind.*"/>

    <!--注解注入-->
    <context:annotation-config/>

    <!--配置JSP视图解析器:定义跳转的文件的前后缀-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

6、entity类-StudentEntity

package com.wind.entity;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
public class StudentEntity implements Serializable {

    private static final long serialVersionUID = 7475710140661551551L;

    private int id;             //学号
    private String name;        //姓名
    private int classId;        //班级
    private int status;         //是否有效(1:有效,-1:无效)
    private Date addTime;       //添加时间
    private Date updateTime;    //更新时间
}

7. Dao layer interface-StudentDao

package com.wind.dao;

import com.wind.entity.StudentEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentDao {

    Integer insertStudent(@Param("studentEntity") StudentEntity studentEntity);

    Integer updateStudent(@Param("studentEntity") StudentEntity studentEntity);

    Integer deleteStudent(@Param("id") int id);

    List<StudentEntity> findAllValidStudent();

    StudentEntity findStudentById(@Param("id") int id);
}

8. The xml file corresponding to the dao layer interface-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.wind.dao.StudentDao">

    <resultMap id="studentMap" type="com.wind.entity.StudentEntity">
        <result column="Id" property="id"/>
        <result column="Name" property="name"/>
        <result column="ClassId" property="classId"/>
        <result column="Status" property="status"/>
        <result column="AddTime" property="addTime"/>
        <result column="UpdateTime" property="updateTime"/>
    </resultMap>

    <sql id="sql_select">
        select Id, Name, ClassId, Status, AddTime, UpdateTime from RUN_Student
    </sql>

    <insert id="insertStudent" parameterType="studentEntity" keyProperty="studentEntity.id" useGeneratedKeys="true">
        insert into RUN_Student
        (
          Id,
          Name,
          ClassId,
          Status
         )
         values
         (
          #{studentEntity.id},
          #{studentEntity.name},
          #{studentEntity.classId},
          1
         )
    </insert>

    <update id="updateStudent" parameterType="studentEntity" useGeneratedKeys="true">
        update RUN_Student set
        Name = #{studentEntity.name},
        ClassId = #{studentEntity.classId},
        Status = 1
        where id = #{studentEntity.id}
    </update>

    <update id="deleteStudent" parameterType="int" useGeneratedKeys="true">
        update RUN_Student set status = -1 where id = #{id}
    </update>

    <select id="findAllValidStudent" resultMap="studentMap">
        <include refid="sql_select"/>
        where status = 1
    </select>

    <select id="findStudentById" parameterType="int" resultMap="studentMap">
        <include refid="sql_select"/>
        where id = #{id} and status = 1
    </select>

</mapper>

9. Service interface service: StudentService

package com.wind.service;

import com.wind.entity.StudentEntity;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface StudentService {
    Integer insertStudent(StudentEntity studentEntity);
    Integer updateStudent(StudentEntity studentEntity);
    Integer deleteStudent(int id);
    List<StudentEntity> findAllStudent();
    StudentEntity findStudentById(int id);
}

10. Implementation of service interface service: StudentServiceImpl

package com.wind.serviceImpl;

import com.wind.dao.StudentDao;
import com.wind.service.StudentService;
import com.wind.entity.StudentEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class StudentServiceImpl implements StudentService {

    private final static Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Resource
    private StudentDao studentDao;

    @Override
    public Integer insertStudent(StudentEntity studentEntity) {
        Integer result = studentDao.insertStudent(studentEntity);
        logger.info("insertStudent result={}", result);
        return result;
    }

    @Override
    public Integer updateStudent(StudentEntity studentEntity) {
        Integer result = studentDao.updateStudent(studentEntity);
        logger.info("updateStudent result={}", result);
        return result;
    }

    @Override
    public Integer deleteStudent(int id) {
        Integer result = studentDao.deleteStudent(id);
        logger.info("deleteStudent result={}", result);
        return result;
    }

    @Override
    public List<StudentEntity> findAllStudent() {
        List<StudentEntity> entities = studentDao.findAllValidStudent();
        logger.info("findAllStudent result={}", (entities != null ? entities.size() : 0));
        return entities;
    }

    @Override
    public StudentEntity findStudentById(int id) {
        StudentEntity studentEntity = studentDao.findStudentById(id);
        logger.info("findStudentById result={}", studentEntity);
        return studentEntity;
    }
}

11. Controller layer interface: StudentController

package com.wind.controller;

import com.wind.entity.StudentEntity;
import com.wind.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;


@Controller
@RequestMapping("/student")
public class StudentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    @Resource
    private StudentService studentService;

    @RequestMapping("findAll")
    public ModelAndView findAll() {
        List<StudentEntity> entities = studentService.findAllStudent();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("student");
        modelAndView.addObject("list", entities);
        logger.info("size={}", entities.size());
        return modelAndView;
    }
}

12. Unit testing

12.1 Unit test base class-BaseTest

package base.test;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public abstract class BaseTest {
}

12.2 Whether the unit test-service interface service is normal

package base.test.service;

import base.test.BaseTest;
import com.wind.entity.StudentEntity;
import com.wind.service.StudentService;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.List;

public class StudentControllerTest extends BaseTest {

    @Resource
    private StudentService studentService;

    @Test
    public void findAllStudentTest() {
        List<StudentEntity> entities = studentService.findAllStudent();
        System.out.println(entities);
    }

    @Test
    public void findStudentByIdTest() {
        int id = 1;
        StudentEntity entity = studentService.findStudentById(id);
        System.out.println(entity);
    }

    @Test
    public void insertStudentTest() {
        int count = 0;
        for (int i = 1; i < 3; i++) {
            StudentEntity entity = new StudentEntity();
            entity.setName("周星驰" + i);
            entity.setClassId(i);
            count = count + studentService.insertStudent(entity);
        }
        System.out.println(count);
    }

    @Test
    public void deleteStudentTest() {
        int count = 0;
        for (int i = 7; i < 13; i++) {
            count = count + studentService.deleteStudent(i);
        }
        System.out.println(count);
    }

    @Test
    public void updateStudentTest() {
        int count = 0;
        for (int i = 7; i < 13; i++) {
            StudentEntity entity = new StudentEntity();
            entity.setId(i);
            entity.setClassId(i - 6);
            entity.setName("周星驰" + "-" + "周润发" + (i - 8));
            count = count + studentService.updateStudent(entity);
        }
        System.out.println(count);
    }
}

12.3 Unit test-whether the Controller interface service is normal

12.3.1 Front-end jsp page

<%--
  Created by IntelliJ IDEA.
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<c:forEach items="${list}" var="student">
    ${student.id}--${student.name}--${student.classId}--${student.status}<br/>
</c:forEach>

</body>
</html>

12.3.2 Front-end access test

 

 

 

Guess you like

Origin blog.csdn.net/cmm0401/article/details/111773736