乐趣区

手把手整合SSM框架

前言

如果看过前几篇文章,对 SpringMyBatis 有了肯定理解,肯定想上手试试。这篇文章从 0 到 1,手把手整合 SSM (Spring、Spring MVC、MyBatis)。

本篇是代码篇,在 PC 端浏览更佳,源码在文末

[toc]

搭建整合 SSM 之 HelloWorld

开发环境

  • idea
  • MySql5.x
  • jdk8
  • maven

对应的技术入门在 公众号 历史文章 都能够找到

目录

目录包含 main、resources、mapper、webapp,不一一介绍,不相熟查看后面文章。

环境搭建

新建我的项目

这里应用的是 IDEA 编辑器,新建一个 Maven 工程,抉择 web 我的项目。

导入依赖

应用 Maven 治理我的项目 jar,只须要在 pom.xml 加如相干依赖即可。

<?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>javapub.rodert.github</groupId>
    <artifactId>ssm_helloword_web</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <url></url>
<!--    源码:https://github.com/Rodert/JavaPub-->

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.3.6.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- 1. 日志 -->
        <!-- 实现 slf4j 接口并整合 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!-- 2. 数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- DAO: MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- 3.Servlet web -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- 4.Spring -->
        <!-- 1)Spring 外围 -->
        <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>
        <!-- 2)Spring DAO 层 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 3)Spring web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 4)Spring test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- redis 客户端:Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.0.8</version>
        </dependency>

        <!-- Map 工具类 -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2</version>
        </dependency>

        <!-- 注解 -->
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


        <build>
            <finalName>ssm_helloword_web</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>7</source>
                        <target>7</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>

</project>
<!--    源码:https://github.com/Rodert/JavaPub-->

编码

配置文件

spring-dao.xml
  • 先在 spring 文件夹里新建 spring-dao.xml 文件,咱们这里分三层,别离是 dao service web。
  1. 加载数据库配置
  2. 配置数据库连接池
  3. 配置 SqlSessionFactory 对象(MyBatis)
  4. 配置扫描 dao 层接口,动静代理实现 Dao 实现类,执行 sql 写在 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"
       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">
    <!-- 配置整合 mybatis 过程 -->
    <!-- 1. 配置数据库相干参数 properties 的属性:${url} -->

    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 2. 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- c3p0 连接池的公有属性 -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- 敞开连贯后不主动 commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 获取连贯超时工夫 -->
        <property name="checkoutTimeout" value="10000" />
        <!-- 当获取连贯失败重试次数 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!-- 3. 配置 SqlSessionFactory 对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置 MyBaties 全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:Mybatis-config.xml" />
        <!-- 扫描 entity 包 应用别名 -->
        <property name="typeAliasesPackage" value="javapub.rodert.github.entity" />
        <!-- 扫描 sql 配置文件:mapper 须要的 xml 文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 4. 配置扫描 Dao 接口包,动静实现 Dao 接口,注入到 spring 容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入 sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出须要扫描 Dao 接口包 -->
        <property name="basePackage" value="javapub.rodert.github.dao" />
    </bean>
</beans>
jdbc.properties

数据库配置,在 resources 文件夹里新建一个 jdbc.properties 文件,留神本人的明码。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm1?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
mybatis-config.xml

MyBatis 外围文件,在 recources 文件夹里新建 mybatis-config.xml 文件。

  1. 应用自增主键
  2. 应用列别名
  3. 开启驼峰命名转换 create_time -> createTime
<?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>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 应用 jdbc 的 getGeneratedKeys 获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 应用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>
spring-service.xml

在 spring 文件夹里新建 spring-service.xml 文件。

  1. 扫描 service 包所有注解 @Service
  2. 配置事务管理器,把事务管理交由 spring 来实现
  3. 基于注解的 申明式事务,能够间接在办法上 @Transaction
<?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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描 service 包下所有应用注解的类型 -->
    <context:component-scan base-package="javapub.rodert.github.service" />

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置基于注解的申明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
spring-web.xml

web 层,在 spring 文件夹里新建 spring-web.xml 文件。

  1. 开启 SpringMVC 注解模式,能够应用 @RequestMapping,@PathVariable,@ResponseBody 等
  2. 对动态资源解决,如 js,css,jpg 等
  3. 配置 jsp 显示 ViewResolver,及渲染后的 JSP
  4. 扫描 web 层 @Controller
<?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-3.0.xsd">
    <!-- 配置 SpringMVC -->
    <!-- 1. 开启 SpringMVC 注解模式 -->
    <!-- 简化配置:(1)主动注册 DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
        (2)提供一些列:数据绑定,数字和日期的 format @NumberFormat, @DateTimeFormat, xml,json 默认读写反对
    -->
    <mvc:annotation-driven />

    <!-- 2. 动态资源默认 servlet 配置
        (1)退出对动态资源的解决:js,gif,png
        (2)容许应用 "/" 做整体映射
     -->
    <mvc:default-servlet-handler/>

    <!-- 3. 配置 jsp 显示 ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<!--        <property name="contentType" value="text/html"/>-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4. 扫描 web 相干的 bean -->
    <context:component-scan base-package="javapub.rodert.github.web" />
</beans>
web.xml

批改 web.xml 文件了,它在 webapp 的 WEB-INF 下。也能够在这里配置过滤器、监听器等。

<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_3_1.xsd"version="3.1"metadata-complete="true">
  <!-- 如果是用 mvn 命令生成的 xml,须要批改 servlet 版本为 3.1 -->
  <!-- 配置 DispatcherServlet -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置 springMVC 须要加载的配置文件
        spring-dao.xml,spring-service.xml,spring-web.xml
        Mybatis - > spring -> springmvc
     -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-*.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>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
日志

配置一些简略的日志,应用 logback,在 resources 文件夹里新建logback.xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are by default assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>
配置阐明

以上配置是整合 SSM 的根底配置,目录构造如图所示:


SSM 实例 - 图书管理系统

sql

以上局部整个 SSM 框架就曾经搭建好了,上面是一个 Demo,供参考。

新建俩张表,图书表 book 和 预约图书表 appointment,并初始化数据。

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50716
Source Host           : localhost:3306
Source Database       : ssm1

Target Server Type    : MYSQL
Target Server Version : 50716
File Encoding         : 65001

Date: 2020-07-12 16:50:43
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for appointment
-- ----------------------------
DROP TABLE IF EXISTS `appointment`;
CREATE TABLE `appointment` (`book_id` bigint(20) NOT NULL COMMENT '图书 ID',
  `student_id` bigint(20) NOT NULL COMMENT '学号',
  `appoint_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '预约工夫',
  PRIMARY KEY (`book_id`,`student_id`),
  KEY `idx_appoint_time` (`appoint_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='预约图书表';

-- ----------------------------
-- Records of appointment
-- ----------------------------

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (`book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图书 ID',
  `name` varchar(100) NOT NULL COMMENT '图书名称',
  `number` int(11) NOT NULL COMMENT '馆藏数量',
  PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8 COMMENT='图书表';

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('2000', 'Java 程序设计', '20');
INSERT INTO `book` VALUES ('2001', '数据结构', '7');
INSERT INTO `book` VALUES ('2002', '设计模式', '20');
INSERT INTO `book` VALUES ('2003', '编译原理', '20');
实体

entity 包下新建实体 BookAppointment

  • Book.java
package javapub.rodert.github.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 20:58
 * @description
 *
 * @Data 注解,简化代码,主动增加 get set toSting 办法
 * @Getter
 * @Setter
 * @ToString
 */
@Getter
@Setter
@ToString
public class Book {

    private long bookId;// 图书 ID

    private String name;// 图书名称

    private int number;// 馆藏数量

    // 省略构造方法,getter 和 setter 办法,toString 办法

}
  • Appointment.java
package javapub.rodert.github.entity;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 20:58
 * @description
 */

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Date;

/**
 * 预约图书实体
 * @Data 注解,简化代码,主动增加 get set toSting 办法
 */
@Data
public class Appointment {

    private long bookId;// 图书 ID

    private long studentId;// 学号

    private Date appointTime;// 预约工夫

    // 多对一的复合属性
    private Book book;// 图书实体

    // 省略构造方法,getter 和 setter 办法,toString 办法

}
dao 接口

dao 包新建接口 BookDao.javaAppointment.java

  • BookDao.java
package javapub.rodert.github.dao;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:01
 * @description
 */

import javapub.rodert.github.entity.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookDao {

    /**
     * 通过 ID 查问单本图书
     *
     * @param id
     * @return
     */
    Book queryById(long id);

    /**
     * 查问所有图书
     *
     * @param offset 查问起始地位
     * @param limit 查问条数
     * @return
     */
    List<Book> queryAll(@Param("offset") int offset, @Param("limit") int limit);

    /**
     * 缩小馆藏数量
     *
     * @param bookId
     * @return 如果影响行数等于 >1,示意更新的记录行数
     */
    int reduceNumber(long bookId);
}
  • AppointmentDao.java
package javapub.rodert.github.dao;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:01
 * @description
 */

import javapub.rodert.github.entity.Appointment;
import org.apache.ibatis.annotations.Param;

public interface AppointmentDao {

    /**
     * 插入预约图书记录
     *
     * @param bookId
     * @param studentId
     * @return 插入的行数
     */
    int insertAppointment(@Param("bookId") long bookId, @Param("studentId") long studentId);

    /**
     * 通过主键查问预约图书记录,并且携带图书实体
     *
     * @param bookId
     * @param studentId
     * @return
     */
    Appointment queryByKeyWithBook(@Param("bookId") long bookId, @Param("studentId") long studentId);

}

提醒 :这里为什么要给办法的参数增加 @Param 注解呢?是因为该办法有两个或以上的参数,肯定要加,不然 mybatis 辨认不了。下面的 BookDao 接口的 queryById 办法和 reduceNumber 办法只有一个参数 book_id,所以能够不必加 @Param 注解。


dao 接口 xml

这里不须要写 dao 接口 的实现类,mybatis 会帮咱们动静实现,下面咱们曾经在 spring-dao.xml 配置了动静扫描。当初须要编写相应的 mapper
mapper 目录里新建两个文件 BookDao.xmlAppointmentDao.xml,别离对应下面两个 dao 接口。

  • BookDao.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="javapub.rodert.github.dao.BookDao">
    <!-- 目标:为 dao 接口办法提供 sql 语句配置 -->
    <select id="queryById" resultType="Book" parameterType="long">
        <!-- 具体的 sql -->
        SELECT
        book_id,
        name,
        number
        FROM
        book
        WHERE
        book_id = #{bookId}
    </select>

    <select id="queryAll" resultType="Book">
        SELECT
            book_id,
            name,
            number
        FROM
            book
        ORDER BY
            book_id
        LIMIT #{offset}, #{limit}
    </select>

    <update id="reduceNumber">
        UPDATE book
        SET number = number - 1
        WHERE
            book_id = #{bookId}
        AND number > 0
    </update>
</mapper>
  • AppointmentDao.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="javapub.rodert.github.dao.AppointmentDao">
    <insert id="insertAppointment">
        <!-- ignore 主键抵触,报错 -->
        INSERT ignore INTO appointment (book_id, student_id)
        VALUES (#{bookId}, #{studentId})
    </insert>

    <select id="queryByKeyWithBook" resultType="Appointment">
        <!-- 如何通知 MyBatis 把后果映射到 Appointment 同时映射 book 属性 -->
        <!-- 能够自在管制 SQL -->
        SELECT
        a.book_id,
        a.student_id,
        a.appoint_time,
        b.book_id "book.book_id",
        b.`name` "book.name",
        b.number "book.number"
        FROM
        appointment a
        INNER JOIN book b ON a.book_id = b.book_id
        WHERE
        a.book_id = #{bookId}
        AND a.student_id = #{studentId}
    </select>
</mapper>

mapper 阐明namespace 是 xml 对应的接口全名,selectupdate 中的 id 对应办法名(惟一),resultType 是返回值类型,parameterType 是参数类型(这个其实可选),#{...} 中填写的是办法的参数


dao 接口测试

当初的写法是从数据库层向前(web)写,当初测试一下 dao 接口,编写测试类。

因为每次测试都要加载配置文件,所有抽离一个类(BaseTest),每次测试方法都继承它。

  • BaseTest.java
package javapub.rodert.github;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:07
 * @description
 */

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

/**
 * 配置 spring 和 junit 整合,junit 启动时加载 springIOC 容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 通知 junit spring 配置文件
@ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"})
public class BaseTest {}

新建 BookDaoTest.javaAppointmentDaoTest.java 两个 dao 测试文件。

  • BookDao.java
package javapub.rodert.github.dao;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:08
 * @description
 */


import javapub.rodert.github.BaseTest;
import javapub.rodert.github.entity.Book;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class BookDaoTest extends BaseTest {

    @Autowired
    private BookDao bookDao;

    @Test
    public void testQueryById() throws Exception {
        long bookId = 1000;
        Book book = bookDao.queryById(bookId);
        System.out.println(book);
    }

    @Test
    public void testQueryAll() throws Exception {List<Book> books = bookDao.queryAll(0, 4);
        for (Book book : books) {System.out.println(book);
        }
    }

    @Test
    public void testReduceNumber() throws Exception {
        long bookId = 1000;
        int update = bookDao.reduceNumber(bookId);
        System.out.println("update=" + update);
    }

}
  • AppointmentDaoTest.java
package javapub.rodert.github.dao;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:18
 * @description
 */


import javapub.rodert.github.BaseTest;
import javapub.rodert.github.entity.Appointment;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class AppointmentDaoTest extends BaseTest {

    @Autowired
    private AppointmentDao appointmentDao;

    @Test
    public void testInsertAppointment() throws Exception {
        long bookId = 1000;
        long studentId = 12345678910L;
        int insert = appointmentDao.insertAppointment(bookId, studentId);
        System.out.println("insert=" + insert);
    }

    @Test
    public void testQueryByKeyWithBook() throws Exception {
        long bookId = 1000;
        long studentId = 12345678910L;
        Appointment appointment = appointmentDao.queryByKeyWithBook(bookId, studentId);
        System.out.println(appointment);
        System.out.println(appointment.getBook());
    }

}
  • BookDaoTest.java — > testQueryById()

测试方法都验证过,没有问题,不一一测试了


业务层 - 后果集封装

到这里,咱们的 dao 层,及数据库接口操作都没有问题,上面开始业务层编写。

如果你有实战我的项目教训,那肯定会发现,对于后端接口,咱们都会定义一个对立的返回格局,及定义一个返回规范不便前端解析,如下:

{
    "code":200,
    "message":"胜利",
    "result":{},
    "isSuccess":true
}

开始写咱们的代码,新建枚举类,用来定义预约业务的数据字典。如果不太明确,先看代码,前面在 JavaPub 微信公众号文章索引中查找对应文章。

新建一个包叫 enums,在外面新建一个枚举类 AppointStateEnum.java

  • AppointStateEnum.java
package javapub.rodert.github.enums;

/**
 * @author wangshiyu rodert
 * @date 2020/7/6 21:20
 * @description
 */


/**
 * 应用枚举表述常量数据字典
 */
public enum AppointStateEnum {SUCCESS(1, "预约胜利"), NO_NUMBER(0, "库存有余"), REPEAT_APPOINT(-1, "反复预约"), INNER_ERROR(-2, "零碎异样");

    private int state;

    private String stateInfo;

    private AppointStateEnum(int state, String stateInfo) {
        this.state = state;
        this.stateInfo = stateInfo;
    }

    public int getState() {return state;}

    public String getStateInfo() {return stateInfo;}

    public static AppointStateEnum stateOf(int index) {for (AppointStateEnum state : values()) {if (state.getState() == index) {return state;}
        }
        return null;
    }

}

dto 包下新建 AppointExecution.java 用来存储咱们执行预约操作的返回后果。

  • AppointExecution.java
package javapub.rodert.github.dto;

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:26
 * @description
 */


import javapub.rodert.github.entity.Appointment;
import javapub.rodert.github.enums.AppointStateEnum;
import lombok.Data;

/**
 * 封装预约执行后后果
 */
@Data
public class AppointExecution {

    // 图书 ID
    private long bookId;

    // 秒杀预约后果状态
    private int state;

    // 状态标识
    private String stateInfo;

    // 预约胜利对象
    private Appointment appointment;

    public AppointExecution() {}

    // 预约失败的结构器
    public AppointExecution(long bookId, AppointStateEnum stateEnum) {
        this.bookId = bookId;
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();}

    // 预约胜利的结构器
    public AppointExecution(long bookId, AppointStateEnum stateEnum, Appointment appointment) {
        this.bookId = bookId;
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
        this.appointment = appointment;
    }

    // 省略 getter 和 setter 办法,toString 办法

}

exception 包下新建三个文件

NoNumberException.java
RepeatAppointException.java
AppointException.java

预约业务异样类(都须要继承 RuntimeException — 运行时异样类),别离是无库存异样、反复预约异样、预约未知谬误异样,用于业务层非胜利状况下的返回(即胜利返回后果,失败抛出异样)。为事务做筹备。

  • AppointException.java
package javapub.rodert.github.exception;

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:31
 * @description
 */

/**
 * 预约业务异样
 */
public class AppointException extends RuntimeException {public AppointException(String message) {super(message);
    }

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

}
  • NoNumberException.java
/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:30
 * @description
 */
package javapub.rodert.github.exception;

/**
 * 库存有余异样
 */
public class NoNumberException extends RuntimeException {public NoNumberException(String message) {super(message);
    }

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

}
  • RepeatAppointException.java

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:31
 * @description
 */
package javapub.rodert.github.exception;

/**
 * 反复预约异样
 */
public class RepeatAppointException extends RuntimeException {public RepeatAppointException(String message) {super(message);
    }

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

}
Service 业务接口代码

在 service 包下新建 BookService.java 图书业务接口。

  • BookService.java

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:32
 * @description
 */
package javapub.rodert.github.service;


import javapub.rodert.github.dto.AppointExecution;
import javapub.rodert.github.entity.Book;

import java.util.List;

/**
 * 业务接口:站在 "使用者" 角度设计接口 三个方面:办法定义粒度,参数,返回类型(return 类型 / 异样)*/
public interface BookService {

    /**
     * 查问一本图书
     *
     * @param bookId
     * @return
     */
    Book getById(long bookId);

    /**
     * 查问所有图书
     *
     * @return
     */
    List<Book> getList();

    /**
     * 预约图书
     *
     * @param bookId
     * @param studentId
     * @return
     */
    AppointExecution appoint(long bookId, long studentId);

}

service.impl 包下新建 BookServiceImpl.java 应用 BookService 接口,并实现外面的办法。

  • BookServiceImpl.java


/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:39
 * @description
 */
package javapub.rodert.github.service.impl;


import javapub.rodert.github.dao.AppointmentDao;
import javapub.rodert.github.dao.BookDao;
import javapub.rodert.github.dto.AppointExecution;
import javapub.rodert.github.entity.Appointment;
import javapub.rodert.github.entity.Book;
import javapub.rodert.github.enums.AppointStateEnum;
import javapub.rodert.github.exception.AppointException;
import javapub.rodert.github.exception.NoNumberException;
import javapub.rodert.github.exception.RepeatAppointException;
import javapub.rodert.github.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 注入 Service 依赖
    @Autowired
    private BookDao bookDao;

    @Autowired
    private AppointmentDao appointmentDao;


    @Override
    public Book getById(long bookId) {return bookDao.queryById(bookId);
    }

    @Override
    public List<Book> getList() {return bookDao.queryAll(0, 1000);
    }

    @Override
    @Transactional
    /**
     * 应用注解管制事务办法的长处:* 1. 开发团队达成统一约定,明确标注事务办法的编程格调
     * 2. 保障事务办法的执行工夫尽可能短,不要交叉其余网络操作,RPC/HTTP 申请或者剥离到事务办法内部
     * 3. 不是所有的办法都须要事务,如只有一条批改操作,只读操作不须要事务管制
     */
    public AppointExecution appoint(long bookId, long studentId) {
        try {
            // 减库存
            int update = bookDao.reduceNumber(bookId);
            if (update <= 0) {// 库存有余
                //return new AppointExecution(bookId, AppointStateEnum.NO_NUMBER);// 谬误写法
                throw new NoNumberException("no number");// 抛出异样,保障触发事务执行
            } else {
                // 执行预约操作
                int insert = appointmentDao.insertAppointment(bookId, studentId);
                if (insert <= 0) {// 反复预约
                    //return new AppointExecution(bookId, AppointStateEnum.REPEAT_APPOINT);// 谬误写法
                    throw new RepeatAppointException("repeat appoint");
                } else {// 预约胜利
                    Appointment appointment = appointmentDao.queryByKeyWithBook(bookId, studentId);
                    return new AppointExecution(bookId, AppointStateEnum.SUCCESS, appointment);
                }
            }
            // 要先于 catch Exception 异样前先 catch 住再抛出,不然自定义的异样也会被转换为 AppointException,导致管制层无奈具体辨认是哪个异样
        } catch (NoNumberException | RepeatAppointException e1) {throw e1;} catch (Exception e) {logger.error(e.getMessage(), e);
            // 所有编译期异样转换为运行期异样
            //return new AppointExecution(bookId, AppointStateEnum.INNER_ERROR);// 谬误写法
            throw new AppointException("appoint inner error:" + e.getMessage());
        }
    }

}

实现类应用了咱们上边定义的异样办法 RepeatAppointException,用于业务层非胜利状况下的返回(即胜利返回后果,失败抛出异样)。触发事务。


测试一下业务层代码,这里演示预约图书业务。

  • BookServiceImplTest.java

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 16:40
 * @description
 */
package javapub.rodert.github.service.impl;


import javapub.rodert.github.BaseTest;
import javapub.rodert.github.dto.AppointExecution;
import javapub.rodert.github.service.BookService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class BookServiceImplTest extends BaseTest {

    @Autowired
    private BookService bookService;

    @Test
    public void testAppoint() throws Exception {
        long bookId = 1001;
        long studentId = 12345678910L;
        AppointExecution execution = bookService.appoint(bookId, studentId);
        System.out.println(execution);
    }

}

测试后果:

首次执行是“预约胜利”,如果再次执行的话,应该会呈现“反复预约”,至此,咱们所有的后盾代码都通过单元测试啦~~ 是不是很开心~


咱们还须要在 dto 包里新建一个封装 json 返回后果的类 Result.java,设计成泛型。

  • Result.java
package javapub.rodert.github.dto;

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 21:00
 * @description
 */

import lombok.Data;

/**
 * 封装 json 对象,所有返回后果都应用它
 */
@Data
public class Result<T> {

    private boolean success;// 是否胜利标记

    private T data;// 胜利时返回的数据

    private String error;// 错误信息

    public Result() {}

    // 胜利时的结构器
    public Result(boolean success, T data) {
        this.success = success;
        this.data = data;
    }

    // 谬误时的结构器
    public Result(boolean success, String error) {
        this.success = success;
        this.error = error;
    }

    // 省略 getter 和 setter 办法 应用注解代替
}
web 层

web 层,也就是 controller 层,咱们在 web 包下新建 BookController.java 文件。

  • BookController.java
package javapub.rodert.github.web;

/**
 * @author wangshiyu rodert
 * @date 2020/7/7 21:05
 * @description
 */


import javapub.rodert.github.dto.AppointExecution;
import javapub.rodert.github.dto.Result;
import javapub.rodert.github.entity.Book;
import javapub.rodert.github.enums.AppointStateEnum;
import javapub.rodert.github.exception.NoNumberException;
import javapub.rodert.github.exception.RepeatAppointException;
import javapub.rodert.github.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping("/book") // url:/ 模块 / 资源 /{id}/ 细分 /seckill/list
public class BookController {private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/test")
    public ModelAndView test(){ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("book/test");
        modelAndView.addObject("key","welcome javaPub");
        return modelAndView;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model) {List<Book> list = bookService.getList();
        model.addAttribute("list", list);
        // list.jsp + model = ModelAndView
        return "list";// WEB-INF/jsp/"list".jsp
    }

    @RequestMapping(value = "/{bookId}/detail", method = RequestMethod.GET)
    private String detail(@PathVariable("bookId") Long bookId, Model model) {if (bookId == null) {return "redirect:/book/list";}
        Book book = bookService.getById(bookId);
        if (book == null) {return "forward:/book/list";}
        model.addAttribute("book", book);
        return "detail";
    }

    //ajax json
    //method = RequestMethod.POST,
    @RequestMapping(value = "/{bookId}/appoint",  produces = {"application/json; charset=utf-8"})
    @ResponseBody
    private Result<AppointExecution> appoint(@PathVariable("bookId") Long bookId, @RequestParam("studentId") Long studentId) {if (studentId == null || studentId.equals("")) {return new Result<>(false, "学号不能为空");
        }
        //AppointExecution execution = bookService.appoint(bookId, studentId);// 谬误写法,不能对立返回,要解决异样(失败)状况
        AppointExecution execution = null;
        try {execution = bookService.appoint(bookId, studentId);
        } catch (NoNumberException e1) {execution = new AppointExecution(bookId, AppointStateEnum.NO_NUMBER);
        } catch (RepeatAppointException e2) {execution = new AppointExecution(bookId, AppointStateEnum.REPEAT_APPOINT);
        } catch (Exception e) {execution = new AppointExecution(bookId, AppointStateEnum.INNER_ERROR);
        }
        return new Result<AppointExecution>(true, execution);
    }

}

目前大多我的项目都是前后端拆散,咱们作为服务端,个别和前端通过接口数据交互(json),像接口办法 appoint,应该增加 @ResponseBody 注解。
测试 controller –> appoint 办法能够通过 curl,如:

curl -H“Accept: application/json; charset=utf-8”-d“studentId=1234567890”localhost:8080/book/1003/appoint

运行我的项目

当初整个我的项目全副实现,配置 tomcat,通过左上角引入 tomcat,抉择咱们的我的项目 ssm。

启动胜利后:

这里对前端代码只写较少部分,具体可参考 BookController –> book/test 接口,有须要帮忙请留言。

  • BookController.java –> book/test
    @RequestMapping(value = "/test")
    public ModelAndView test(){ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("book/test");
        modelAndView.addObject("key","welcome javaPub");
        return modelAndView;
    }
  • test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<!DOCTYPE HTML>
<html>
<head>
    <%@ page isELIgnored="false"%>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title>news detail</title>

</head>
<body class="fn-pd24">
<h1> 大家好 ${key}</h1>

<a href="https://mp.weixin.qq.com/s/kfyRAPnRDp8LLktjgd658Q">JavaPub 常识清单 </a>
</body>
</html>

通过 ModelAndView 将咱们须要渲染的数据存储传输到对应视图,由 Sping MVC 定义好的视图解析器对该对象解析,最初将后果数据显示到指定页面。

残缺代码地址:https://github.com/Rodert/Jav…

最初:知识点总结

文章底部都有对应 原创 PDF,继续更新中,
教程纯手打,致力于最实用教程,微信搜:JavaPub,无套路支付收费原创 PDF、学习路线图,后盾回复【666】。

  • 51 页 MyBatis
  • 19 页 Maven
  • 14 页 zookeeper
  • 10 页 Git
  • 18 页 spring
  • 8 页布隆过滤器
  • 50 页排序算法
  • redis 系列文章
  • dubbo
  • nginx
  • ffmpeg
  • Jenkins
  • http

感觉文章内容不错,记得点赞或在看都行,这是对我最大的激励!

退出移动版