Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)

时间:2022-05-15 23:15:27

项目结构:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)

 

 (代码里面都有注释)

一、在pom文件中依赖jar包

因为我这里分了模块,所以有父子级的共两个pom文件

父级:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?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>edu.nf</groupId>
    <artifactId>conformity</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>ch01</module>
        <module>ch02</module>
        <module>ch03</module>
        <module>ch04</module>
        <module>ch05</module>
    </modules>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        <!-- 版本管理 -->
        <spring.version>5.1.1.RELEASE</spring.version>
        <junit.version>4.12</junit.version>
        <druid.version>1.1.10</druid.version>
        <mysql.version>5.1.47</mysql.version>
        <mybatis.version>3.4.6</mybatis.version>
        <mybatis.spring.version>1.3.2</mybatis.spring.version>
        <pagehelper.version>5.1.2</pagehelper.version>
        <aspect.version>1.9.1</aspect.version>
        <servlet.version>4.0.1</servlet.version>
        <jackson.version>2.9.6</jackson.version>
        <slf4j.version>1.7.25</slf4j.version>
    </properties>

    <!-- 依赖管理,子模块按需依赖 -->
    <dependencyManagement>
        <dependencies>
            <!-- javax.servlet-api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet.version}</version>
                <scope>provided</scope>
            </dependency>
            <!-- spring-web -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- spring-webmvc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <!-- spring-jdbc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- spring-tx -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- mybatis整合spring插件 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis.spring.version}</version>
            </dependency>
            <!-- pagehelper分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>${pagehelper.version}</version>
            </dependency>
            <!-- aspectjweaver-->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspect.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- 公共依赖 -->
    <dependencies>
        <!-- spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
</project>
View Code

子级:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?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">
    <parent>
        <artifactId>conformity</artifactId>
        <groupId>edu.nf</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>ch04</artifactId>
    <packaging>war</packaging>

    <dependencies>
        <!-- javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <!-- spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <!-- mybatis整合spring插件 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </dependency>
        <!-- 分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
        </dependency>
        <!-- spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <!-- spring-tx-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
    </dependencies>

    <!-- war插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <warSourceDirectory>web</warSourceDirectory>
                    <!-- 指定web.xml路径 -->
                    <webXml>web\WEB-INF\web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
View Code

ssm所需jar包:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)

 

二、配置web.xml文件

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 当初始化不同的配置文件时,spring会初始化不同的容器对象,
     也就是会产生父子容器,子容器可以共享父容器的内容,但父容器是不能
     访问子容器的对象-->

    <!-- 配置监听器去初始化applicationContext.xml -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 配置监听器的初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    
    <!-- 配置Spring提供的字符编码过滤器 -->
    <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>
        <!-- 让response的编码和request保持一致-->
        <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>

    <!-- WebStatFilter用于采集监控的数据-->
    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置StatViewServlet,用于启用监控视图 -->
    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        <init-param>
            <!-- 用户名 -->
            <param-name>loginUsername</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <!-- 密码 -->
            <param-name>loginPassword</param-name>
            <param-value>root</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

    <!-- 配置核心控制器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 初始化mvc配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
View Code

 

三、配置dispatcher-servlet.xml

创建Springmvc核心配置文件

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 扫描相应的控制器组件,不包含Service以及Dao -->
    <context:component-scan base-package="edu.nf.ch04.controller"/>

    <!-- 启用mvc注解驱动-->
    <mvc:annotation-driven/>

    <!-- 静态资源处理-->
    <mvc:default-servlet-handler/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>
View Code

 

四、配置applicationContext.xml

创建Spring核心配置文件

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
       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://mybatis.org/schema/mybatis-spring
       http://mybatis.org/schema/mybatis-spring.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 启用注解并扫描 -->
    <context:component-scan base-package="edu.nf.ch04">
        <!-- 排除控制层组件,也就是排除带有@Controller注解的类 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置数据源连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 数据库连接属性 -->
        <property name="url" value="jdbc:mysql://localhost:3306/homework?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <!-- 启用系统监控过滤器 -->
        <property name="filters" value="stat"/>
        <!-- 最大连接池数量 -->
        <property name="maxActive" value="200"/>
        <!-- 初始化时建立物理连接的个数-->
        <property name="initialSize" value="5"/>
        <!-- 最小连接池数量-->
        <property name="minIdle" value="5"/>
        <!-- 获取连接时最大等待时间,单位毫秒-->
        <property name="maxWait" value="60000"/>
        <!-- 销毁线程会检测连接的间隔时间,(单位毫秒)
        如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接-->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 连接保持空闲而不被驱逐的最小时间 -->
        <property name="minEvictableIdleTimeMillis" value="300000"/>
        <!--申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
        执行validationQuery检测连接是否有效-->
        <property name="testWhileIdle" value="true"/>
        <!-- 申请连接时执行validationQuery检测连接是否有效 -->
        <property name="testOnBorrow" value="false"/>
        <!-- 归还连接时执行validationQuery检测连接是否有效-->
        <property name="testOnReturn" value="false"/>
        <!-- 是否缓存preparedStatement, mysql建议关闭-->
        <property name="poolPreparedStatements" value="false"/>
        <!-- 伪SQL,用于检查连接是否可用 -->
        <property name="validationQuery" value="select 1"/>
    </bean>

    <!-- 配置SqlSessionFactory,将mybatis的SqlSessionFactory交给Spring容器管理 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入druid数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 给实体包下的类定义默认别名-->
        <property name="typeAliasesPackage" value="edu.nf.ch04.entity"/>
        <!-- 指定mapper映射配置文件的目录-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- 配置分页插件-->
        <property name="plugins">
            <!-- 配置一个bean,指定分页插件的拦截器-->
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    <!--配置拦截器的参数属性 -->
                    <props>
                        <!-- 指定数据库方言 -->
                        <prop key="helperDialect">mysql</prop>
                        <!-- 分页参数使用注解支持-->
                        <prop key="supportMethodsArguments">true</prop>
                    </props>
                </property>
            </bean>
        </property>
    </bean>

    <!-- 指定扫描的dao接口的包,利用动态代理在运行时生成dao的实现类 -->
    <mybatis:scan base-package="edu.nf.ch04.dao"/>

    <!-- 装配DataSource的事务管理器-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 需要注入一个DataSource -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 启用事务注解驱动,transaction-manager引用上面定义的事务管理器的id,
    如果id的名称就叫做transactionManager,那么就不需要指定这个属性,因为是默认值-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>
View Code

mapper:ClassDao.xml 数据库执行语句

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?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="edu.nf.ch04.dao.ClassDao">

    <resultMap id="classMap" type="classInfo">
        <id property="id" column="c_id"/>
        <result property="className" column="c_name"/>
    </resultMap>

    <select id="listClassInfo" resultMap="classMap">
        select * from class_info
    </select>

    <select id="getClassById" parameterType="integer" resultMap="classMap">
        select * from class_info where c_id = #{id}
    </select>

    <insert id="saveClassInfo" parameterType="classInfo">
        insert into class_info(c_name) values(#{className});
    </insert>

    <update id="updateClassInfo" parameterType="classInfo">
        update class_info set c_name = #{className}
    </update>

</mapper>
View Code

五、Log4j日志的配置:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>

    <!-- 指定日志的输出方式,ConsoleAppender表示输出到控制台 -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <!-- 使用自定义布局-->
        <layout class="org.apache.log4j.PatternLayout">
            <!-- 自定义布局转换参数说明
                 %d 日期格式
                 %p 输出级别
                 %t 输出当先执行线程名
                 %M 输出当先运行的方法名
                 %l 输出日志事件的发生位置,包括类名、发生的线程,以及在代码中的行数
                 %c 输出当前的类名
                 %m 输出日志内容
                 %n 换行-->
            <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss} %-5p] [%t] %l - %m%n" />
        </layout>
        <!-- 过滤输出范围-->
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="levelMin" value="debug" />
            <param name="levelMax" value="error" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <!-- 配置log4j的root,默认所有日志都将以root的配置进行输出-->
    <root>
        <!-- 指定输出级别,log4j一共分为7个级别,由低到高分为ALL、DEBUG、INFO、WARN、ERROR、FATAL、OFF
             但官方建议使用DEBUG、INFO、WARN、ERROR这4个级别。通过使用日志级别,可以控制应用程序中相应级别日志信息的输出。
             例如,如果使用了info级别,则应用程序中所有低于info级别的日志信息(如debug)将不会被打印出来。-->
        <priority value ="debug"/>
        <!-- 引用输出方式,ref对应appender的name -->
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>
View Code

 

六、编写代码

Controller

BaseController:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.controller;

import edu.nf.ch04.controller.vo.ResponseVO;

/**
 * @author wangl
 * @date 2018/11/12
 * 父级控制器
 * 封装了给子类调用的成功响应视图的方法
 */
public class BaseController {

    protected ResponseVO success(){
        return new ResponseVO();
    }

    protected ResponseVO success(Object value){
        ResponseVO vo = new ResponseVO();
        vo.setValue(value);
        return vo;
    }

    protected ResponseVO success(Integer code, Object value){
        ResponseVO vo = new ResponseVO();
        vo.setCode(code);
        vo.setValue(value);
        return vo;
    }
}
View Code

ClassController:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.controller;

import edu.nf.ch04.controller.vo.ResponseVO;
import edu.nf.ch04.entity.ClassInfo;
import edu.nf.ch04.servie.ClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/12
 */
@Controller
public class ClassController extends BaseController{

    /**
     * 日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(ClassController.class);

    /**
     * 注入对象
     */
    @Autowired
    private ClassService classService;

    @GetMapping("/listClassInfo")
    @ResponseBody
    public ResponseVO listClassInfo(Integer pageNum, Integer pageSize){
        List<ClassInfo> list = classService.listClassInfo(pageNum, pageSize);
        logger.info("查询用户列表: " + list.size());
        return success(list);
    }

    @PostMapping("/add")
    public ResponseVO addClass(ClassInfo classInfo){
        classService.saveClassInfo(classInfo);
        return success();
    }
}
View Code

advice(GlobalExceptionHandler):异常处理类

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.controller.advice;


import edu.nf.ch04.controller.vo.ResponseVO;
import edu.nf.ch04.servie.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wangl
 * @date 2018/11/12
 * 定义一个全局的异常处理类(类似一个切面)
 * 这个类中定义的所有方法都是异常处理方法,
 * 也可以理解为是全局的异常通知
 * value属性指定对哪些控制器进行切入拦截
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常处理方法
     * 用于处理参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public ResponseVO handleDataAccessException(DataAccessException e){
        ResponseVO vo = new ResponseVO();
        //设置相应状态码以及异常信息
        vo.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        vo.setMessage(e.getMessage());
        return vo;
    }
}
View Code

vo响应视图

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.controller.vo;

import org.springframework.http.HttpStatus;

/**
 * @author wangl
 * @date 2018/11/12
 * 响应视图
 */
public class ResponseVO {

    private Integer code = HttpStatus.OK.value();

    private String message;

    private Object value;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "ResponseVO{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", value=" + value +
                '}';
    }
}
View Code

Service

自定义异常DataAccessException:

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.servie;

/**
 * @author wangl
 * @date 2018/11/12
 */
public class DataAccessException extends RuntimeException{

    public DataAccessException(String message) {
        super(message);
    }

    public DataAccessException(String message, Throwable cause) {
        super(message, cause);
    }

    public DataAccessException(Throwable cause) {
        super(cause);
    }
}
View Code

业务层 接口ClassService

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.servie;

import edu.nf.ch04.entity.ClassInfo;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 */
public interface ClassService {

    /**
     * 查询班级信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    List<ClassInfo> listClassInfo(Integer pageNum, Integer pageSize);

    /**
     * 根据id查询班级信息
     * @param id
     * @return
     */
    ClassInfo getClassById(Integer id);

    /**
     * 新建班级信息
     * @param classInfo
     */
    void saveClassInfo(ClassInfo classInfo);

    /**
     * 修改班级信息
     * @param classInfo
     */
    void updateClassInfo(ClassInfo classInfo);
}
View Code

业务层 实现类ClassServiceImpl

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.servie.impl;

import edu.nf.ch04.dao.ClassDao;
import edu.nf.ch04.entity.ClassInfo;
import edu.nf.ch04.servie.ClassService;
import edu.nf.ch04.servie.DataAccessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 * @Transactional 事务注解
 */
@Service("classService")
@Transactional(rollbackFor = RuntimeException.class)
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassDao classDao;

    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<ClassInfo> listClassInfo(Integer pageNum, Integer pageSize) {
        return classDao.listClassInfo(pageNum, pageSize);
    }

    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public ClassInfo getClassById(Integer id) {
        return classDao.getClassById(id);
    }

    @Override
    public void saveClassInfo(ClassInfo classInfo) {
        try {
            classDao.saveClassInfo(classInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new DataAccessException("添加失败");
        }
    }

    @Override
    public void updateClassInfo(ClassInfo classInfo) {
        try {
            classDao.updateClassInfo(classInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("修改失败");
        }
    }
}
View Code

Dao(ClassDao持久层 接口)

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.dao;

import edu.nf.ch04.entity.ClassInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author wangl
 * @date 2018/11/8
 */
@Repository
public interface ClassDao {

    /**
     * 查询班级列表信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    List<ClassInfo> listClassInfo(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize);

    /**
     * 根据id查询班级信息
     * @param id
     * @return
     */
    ClassInfo getClassById(Integer id);

    /**
     * 新建班级信息
     * @param classInfo
     */
    void saveClassInfo(ClassInfo classInfo);

    /**
     * 修改班级信息
     * @param classInfo
     */
    void updateClassInfo(ClassInfo classInfo);
}
View Code

Entity(ClassInfo 实体类)

Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)Spring+Spring MVC+Mybatis 框架整合开发(半注解半配置文件)
package edu.nf.ch04.entity;

/**
 * @author wangl
 * @date 2018/11/8
 */
public class ClassInfo {

    private Integer id;

    private String className;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "id=" + id +
                ", className='" + className + '\'' +
                '}';
    }
}
View Code