手把手整合SSM框架2

简介: 手把手整合SSM框架

手把手整合SSM框架1:https://developer.aliyun.com/article/1536306

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/JavaPub/

最后:知识点总结

文章底部都有对应原创PDF,持续更新中,

教程纯手打,致力于最实用教程,

目录
相关文章
|
7月前
|
Java
SSM框架整合
SSM框架整合
51 3
|
4月前
|
Java 数据库连接 Maven
手把手教你如何搭建SSM框架、图书商城系统案例
这篇文章是关于如何搭建SSM框架以及实现一个图书商城系统的详细教程,包括了项目的配置文件整合、依赖管理、项目结构和运行效果展示,并提供了GitHub源码链接。
手把手教你如何搭建SSM框架、图书商城系统案例
|
6月前
|
Java 数据库连接 Maven
手把手整合SSM框架1
手把手整合SSM框架
108 0
|
4月前
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
4月前
|
Java 数据库连接 Maven
SSM框架整合图书管理项目
这篇文章是关于SSM框架整合到图书管理项目的详细教程,涵盖了从Maven项目构建、依赖导入、数据库连接、配置文件编写、实体类和接口实现到SpringMVC整合的完整步骤。
SSM框架整合图书管理项目
|
3月前
|
XML Java 数据库连接
如何搭建SSM框架、图书商城系统
这是一份详尽的《Spring + SpringMVC + Mybatis 整合指南》,作者耗时良久整理出约五万字的内容,现已经全部笔记公开。此文档详细地介绍了如何搭建与整合SSM框架,具体步骤包括创建Maven项目、添加web骨架、配置pom文件以及整合Spring、SpringMVC和Mybatis等。无论是对初学者还是有一定基础的开发者来说,都是很好的学习资源。此外,作者还提供了项目源码的GitHub链接,方便读者实践。虽然当前主流推荐学习SpringBoot,但了解SSM框架仍然是不可或缺的基础。
50 0
|
4月前
|
Java 数据库
使用ssm框架搭建的图书管理系统
本文介绍了使用SSM框架搭建的图书管理系统,包括图书信息管理、借阅记录管理、公告管理、出入库管理以及用户管理等功能。
使用ssm框架搭建的图书管理系统
|
6月前
|
SQL 前端开发 Java
基于SSM框架的教务系统
基于SSM框架的教务系统
59 2
基于SSM框架的教务系统
|
6月前
|
Java
SSM框架Controller层可以做什么
SSM框架Controller层可以做什么
|
6月前
|
存储 Java 关系型数据库
基于SSM框架的电影院售票网站
基于SSM框架的电影院售票网站
基于SSM框架的电影院售票网站
下一篇
DataWorks