SSM框架整合

手把手教你整合最优雅SSM框架:SpringMVC + Spring + MyBatis

原文链接

我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能;而且在大部分教学课堂中,也会把SSH作为最核心的教学内容。 
但是,我们在实际应用中发现,SpringMVC可以完全替代Struts,配合注解的方式,编程非常快捷,而且通过restful风格定义url,让地址看起来非常优雅。 
另外,MyBatis也可以替换hibernate,正因为MyBatis的半自动特点,我们程序猿可以完全掌控SQL,这会让有数据库经验的程序猿能开发出高效率的SQL语句,而且XML配置管理起来也非常方便。 
好了,如果你也认同我的看法,那么下面我们一起来做整合吧!

在写代码之前我们先了解一下这三个框架分别是干什么的? 
相信大以前也看过不少这些概念,我这就用大白话来讲,如果之前有了解过可以跳过这一大段,直接看代码!

  1. SpringMVC:它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只反馈josn/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!!

  2. spring:太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们Java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。

  3. MyBatis:如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦~捂脸~)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。


SSM框架整合配置

好了,前面bb那么多,下面我们真正开始敲代码了~

首先我们打开IED,我这里用的是eclipse(你们应该也是用的这个,对吗?),创建一个动态web项目,建立好相应的目录结构(重点!)

项目结构图

(打了马赛克是因为这里还用不到,你们不要那么污好不好?)

我说一下每个目录都有什么用吧(第一次画表格,我发现markdown的表格语法很不友好呀~) 
这个目录结构同时也遵循maven的目录规范~

文件名作用
src根目录,没什么好说的,下面有main和test。
  • main
主要目录,可以放java代码和一些资源文件。
    • java
存放我们的java代码,这个文件夹要使用Build Path -> Use as Source Folder,这样看包结构会方便很多,新建的包就相当于在这里新建文件夹咯。
    • resources
存放资源文件,譬如各种的spring,mybatis,log配置文件。
      • mapper
存放dao中每个方法对应的sql,在这里配置,无需写daoImpl。
      • spring
这里当然是存放spring相关的配置文件,有dao service web三层。
      • sql
其实这个可以没有,但是为了项目完整性还是加上吧。
      • webapp
这个貌似是最熟悉的目录了,用来存放我们前端的静态资源,如jsp js css。
      • resources
这里的资源是指项目的静态资源,如js css images等。
      • WEB-INF
很重要的一个目录,外部浏览器无法访问,只有羡慕内部才能访问,可以把jsp放在这里,另外就是web.xml了。你可能有疑问了,为什么上面java中的resources里面的配置文件不妨在这里,那么是不是会被外部窃取到?你想太多了,部署时候基本上只有webapp里的会直接输出到根目录,其他都会放入WEB-INF里面,项目内部依然可以使用classpath:XXX来访问,好像IDE里可以设置部署输出目录,这里扯远了~
  • test
这里是测试分支。
    • java
测试java代码,应遵循包名相同的原则,这个文件夹同样要使用Build Path -> Use as Source Folder,这样看包结构会方便很多。
    • resources
没什么好说的,好像也很少用到,但这个是maven的规范。

我先新建好几个必要的,并为大家讲解一下每个包的作用,顺便理清一下后台的思路~

包结构图

包名名称作用
dao数据访问层(接口)与数据打交道,可以是数据库操作,也可以是文件读写操作,甚至是redis缓存操作,总之与数据操作有关的都放在这里,也有人叫做dal或者数据持久层都差不多意思。为什么没有daoImpl,因为我们用的是mybatis,所以可以直接在配置文件中实现接口的每个方法。
entity实体类一般与数据库的表相对应,封装dao层取出来的数据为一个对象,也就是我们常说的pojo,一般只在dao层与service层之间传输。
dto数据传输层刚学框架的人可能不明白这个有什么用,其实就是用于service层与web层之间传输,为什么不直接用entity(pojo)?其实在实际开发中发现,很多时间一个entity并不能满足我们的业务需求,可能呈现给用户的信息十分之多,这时候就有了dto,也相当于vo,记住一定不要把这个混杂在entity里面,答应我好吗?
service业务逻辑(接口)写我们的业务逻辑,也有人叫bll,在设计业务接口时候应该站在“使用者”的角度。额,不要问我为什么这里没显示!IDE调皮我也拿它没办法~
serviceImpl业务逻辑(实现)实现我们业务接口,一般事务控制是写在这里,没什么好说的。
web控制器springmvc就是在这里发挥作用的,一般人叫做controller控制器,相当于struts中的action。

还有最后一步基础工作,导入我们相应的jar包,我使用的是maven来管理我们的jar,所以只需要在poom.xml中加入相应的依赖就好了,如果不使用maven的可以自己去官网下载相应的jar,放到项目WEB-INF/lib目录下。关于maven的学习大家可以看慕课网的视频教程,这里就不展开了。我把项目用到的jar都写在下面,版本都不是最新的,大家有经验的话可以自己调整版本号。另外,所有jar都会与项目一起打包放到我的github上,喜欢的给个star吧~

poom.xml

  1. <modelVersion>4.0.0 <groupId>com.soecode.ssm <artifactId>ssm <packaging>war <version>0.0.1-SNAPSHOT <name>ssm Maven Webapp <url>http://github.com/liyifeng1994/ssm <dependencies>
  2. <dependency>
  3. </groupId>
  4. </artifactId>
  5. </version>
  6. <!-- 1.日志 -->
  7. <dependency>
  8. </groupId>
  9. </artifactId>
  10. </version>
  11. <!-- 2.数据库 -->
  12. <groupId>mysql <artifactId>mysql-connector-java <version>5.1.37 <scope>runtime </dependency>
  13. <groupId>c3p0 <artifactId>c3p0 <version>0.9.1.2 </dependency>
  14. <dependency>
  15. </groupId>
  16. </artifactId>
  17. </version>
  18. <dependency>
  19. </groupId>
  20. </artifactId>
  21. </version>
  22. <!-- 3.Servlet web -->
  23. <groupId>taglibs <artifactId>standard <version>1.1.2 </dependency>
  24. <groupId>jstl <artifactId>jstl <version>1.2 </dependency>
  25. <groupId>com.fasterxml.jackson.core <artifactId>jackson-databind <version>2.5.4 </dependency>
  26. <groupId>javax.servlet <artifactId>javax.servlet-api <version>3.1.0 </dependency>
  27. <!-- 1)Spring核心 -->
  28. <groupId>org.springframework <artifactId>spring-core <version>4.1.7.RELEASE </dependency>
  29. <groupId>org.springframework <artifactId>spring-beans <version>4.1.7.RELEASE </dependency>
  30. <groupId>org.springframework <artifactId>spring-context <version>4.1.7.RELEASE </dependency>
  31. <dependency>
  32. </groupId>
  33. </artifactId>
  34. </version>
  35. <dependency>
  36. </groupId>
  37. </artifactId>
  38. </version>
  39. <!-- 3)Spring web -->
  40. <groupId>org.springframework <artifactId>spring-web <version>4.1.7.RELEASE </dependency>
  41. <groupId>org.springframework <artifactId>spring-webmvc <version>4.1.7.RELEASE </dependency>
  42. <dependency>
  43. </groupId>
  44. </artifactId>
  45. </version>
  46. <!-- redis客户端:Jedis -->
  47. <groupId>redis.clients <artifactId>jedis <version>2.7.3 </dependency>
  48. <groupId>com.dyuproject.protostuff <artifactId>protostuff-core <version>1.0.8 </dependency>
  49. <groupId>com.dyuproject.protostuff <artifactId>protostuff-runtime <version>1.0.8 </dependency>
  50. <dependency>
  51. </groupId>
  52. </artifactId>
  53. </version>
  54. </dependencies>
  55. <finalName>ssm </build>
  56. <?xml version="1.0" encoding="UTF-8"?>
  57. <span class="hljs-tag" ;="" border:="" 0px;="" outline:="" vertical-align:="" baseline;="" background:="" transparent;"="" style="outline: 0px; word-break: break-all; margin: 0px; padding: 0px; font-family: "Microsoft YaHei";"> < beans xmlns = "http://www.springframework.org/schema/beans"
  58. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context"
  59. xsi:schemaLocation = "http://www.springframework.org/schema/beans
  60. http://www.springframework.org/schema/beans/spring-beans.xsd
  61. http://www.springframework.org/schema/context
  62. http://www.springframework.org/schema/context/spring-context.xsd" >
  63. <!-- 1.配置数据库相关参数properties的属性:${url} -->
  64. <!-- 2.数据库连接池 -->
  65. <!-- 配置连接池属性 -->
  66. <property name="jdbcUrl" value="${jdbc.url}" />
  67. <property name="password" value="${jdbc.password}" />
  68. <property name="maxPoolSize" value="30" />
  69. <!-- 关闭连接后不自动commit -->
  70. <!-- 获取连接超时时间 -->
  71. <!-- 当获取连接失败重试次数 -->
  72. </bean>
  73. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  74. <property name="dataSource" ref="dataSource" />
  75. <property name="configLocation" value="classpath:mybatis-config.xml" />
  76. <property name="typeAliasesPackage" value="com.soecode.lyf.entity" />
  77. <property name="mapperLocations" value="classpath:mapper/*.xml" />
  78. <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
  79. <!-- 注入sqlSessionFactory -->
  80. <!-- 给出需要扫描Dao接口包 -->
  81. </bean>
  82. <?xml version="1.0" encoding="UTF-8" ?>
  83. <configuration>
  84. <settings>
  85. <setting name="useGeneratedKeys" value="true" />
  86. <setting name="useColumnLabel" value="true" />
  87. <setting name="mapUnderscoreToCamelCase" value="true" />
  88. </configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

第二步:刚弄好dao层,接下来到service层了。在spring文件夹里新建spring-service.xml文件。

  1. 扫描service包所有注解 @Service
  2. 配置事务管理器,把事务管理交由spring来完成
  3. 配置基于注解的声明式事务,可以直接在方法上@Transaction

spring-service.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context = "http://www.springframework.org/schema/context"
  4. xmlns:tx = "http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation = "http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd
  9. http://www.springframework.org/schema/tx
  10. http://www.springframework.org/schema/tx/spring-tx.xsd" >
  11. <context:component-scan base-package="com.soecode.lyf.service" />
  12. <bean id="transactionManager"
  13. class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  14. <property name="dataSource" ref="dataSource" />
  15. <!-- 配置基于注解的声明式事务 -->
  16. </beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

第三步:配置web层,在spring文件夹里新建spring-web.xml文件。

  1. 开启SpringMVC注解模式,可以使用@RequestMapping,@PathVariable,@ResponseBody等
  2. 对静态资源处理,如js,css,jpg等
  3. 配置jsp 显示ViewResolver,例如在controller中某个方法返回一个string类型的”login”,实际上会返回”/WEB-INF/login.jsp”
  4. 扫描web层 @Controller

spring-web.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:context = "http://www.springframework.org/schema/context"
  4. xmlns:mvc = "http://www.springframework.org/schema/mvc"
  5. xsi:schemaLocation = "http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd
  9. http://www.springframework.org/schema/mvc
  10. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd" >
  11. <!-- 1.开启SpringMVC注解模式 -->
  12. <mvc:annotation-driven />
  13. <mvc:default-servlet-handler/>
  14. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  15. <property name="prefix" value="/WEB-INF/jsp/" />
  16. </bean>
  17. <context:component-scan base-package="com.soecode.lyf.web" />
  18. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  19. xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee
  20. http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  21. version = "3.1" metadata-complete = "true" >
  22. <!-- 配置DispatcherServlet -->
  23. <servlet-name>seckill-dispatcher <servlet-class>org.springframework.web.servlet.DispatcherServlet <!-- 配置springMVC需要加载的配置文件
  24. spring-dao.xml,spring-service.xml,spring-web.xml
  25. Mybatis - > spring -> springmvc
  26. -->
  27. <param-name>contextConfigLocation <param-value>classpath:spring/spring-*.xml </init-param>
  28. <servlet-mapping>
  29. </servlet-name>
  30. <url-pattern>/ </servlet-mapping>
  31. <?xml version="1.0" encoding="UTF-8"?>
  32. <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  33. <encoder>
  34. </pattern>
  35. </appender>
  36. <appender-ref ref="STDOUT" />
  37. </configuration>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

到目前为止,我们一共写了7个配置文件,我们一起来看下最终的配置文件结构图

配置文件结构图


SSM框架应用实例(图书管理系统)

一开始想就这样结束教程,但是发现其实很多人都还不会把这个SSM框架用起来,特别是mybatis部分。那我现在就以最常见的“图书管理系统”中【查询图书】和【预约图书】业务来做一个demo吧!

首先新建数据库名为ssm,再创建两张表:图书表book和预约图书表appointment,并且为book表初始化一些数据,sql如下。

schema.sql

  1. CREATE TABLE `book` (
  2. `book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图书ID',
  3. `name` varchar(100) NOT NULL COMMENT '图书名称',
  4. `number` int(11) NOT NULL COMMENT '馆藏数量',
  5. PRIMARY KEY (`book_id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='图书表'
  7. -- 初始化图书数据
  8. INSERT INTO `book` (`book_id`, `name`, `number`)
  9. VALUES
  10. (1000, 'Java程序设计', 10),
  11. (1001, '数据结构', 10),
  12. (1002, '设计模式', 10),
  13. (1003, '编译原理', 10)
  14. -- 创建预约图书表
  15. CREATE TABLE `appointment` (
  16. `book_id` bigint(20) NOT NULL COMMENT '图书ID',
  17. `student_id` bigint(20) NOT NULL COMMENT '学号',
  18. `appoint_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '预约时间' ,
  19. PRIMARY KEY (`book_id`, `student_id`),
  20. INDEX `idx_appoint_time` (`appoint_time`)
  21. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='预约图书表'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

entity包中添加两个对应的实体,图书实体Book.java和预约图书实体Appointment.java

Book.java

  1. public private // 图书ID
  2. // 图书名称
  3. int number; // 省略构造方法,getter和setter方法,toString方法
  4. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Appointment.java

  1. import java.util.Date;
  2. public private // 图书ID
  3. long studentId; private Date appointTime; // 多对一的复合属性
  4. // 图书实体
  5. package com.soecode.lyf.dao;
  6. import com.soecode.lyf.entity.Book;
  7. interface BookDao {
  8. long id);
  9. @Param ( int offset, "limit" ) /**
  10. * 减少馆藏数量
  11. *
  12. * @param bookId
  13. * @return 如果影响行数等于>1,表示更新的记录行数
  14. */
  15. long bookId);
  16. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

AppointmentDao.java

  1. import org.apache.ibatis.annotations.Param;
  2. public /**
  3. * 插入预约图书记录
  4. *
  5. * @param bookId
  6. * @param studentId
  7. * @return 插入的行数
  8. */
  9. @Param ( long bookId, "studentId" ) /**
  10. * 通过主键查询预约图书记录,并且携带图书实体
  11. *
  12. * @param bookId
  13. * @param studentId
  14. * @return
  15. */
  16. Appointment queryByKeyWithBook( "bookId" ) @Param ( long studentId);
  17. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

提示:这里为什么要给方法的参数添加@Param注解呢?是因为该方法有两个或以上的参数,一定要加,不然mybatis识别不了。上面的BookDao接口的queryById方法和reduceNumber方法只有一个参数book_id,所以可以不用加 @Param注解,当然加了也无所谓~


注意,这里不需要实现dao接口不用编写daoImpl, mybatis会给我们动态实现,但是我们需要编写相应的mapper。 
mapper目录里新建两个文件BookDao.xmlAppointmentDao.xml,分别对应上面两个dao接口,代码如下。

BookDao.xml

  1. <!DOCTYPE mapper
  2. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <!-- 目的:为dao接口方法提供sql语句配置 -->
  5. <!-- 具体的sql -->
  6. SELECT
  7. book_id,
  8. name,
  9. number
  10. FROM
  11. book
  12. WHERE
  13. book_id = #{bookId}
  14. <select id="queryAll" resultType="Book">
  15. SELECT
  16. book_id,
  17. name,
  18. number
  19. FROM
  20. book
  21. ORDER BY
  22. book_id
  23. LIMIT #{offset}, #{limit}
  24. <update id="reduceNumber">
  25. UPDATE book
  26. SET number = number - 1
  27. WHERE
  28. book_id = #{bookId}
  29. AND number > 0
  30. </mapper>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

AppointmentDao.xml

  1. <!DOCTYPE mapper
  2. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <insert id="insertAppointment">
  5. </insert>
  6. <!-- 如何告诉MyBatis把结果映射到Appointment同时映射book属性 -->
  7. </select>
  8. package com.soecode.lyf;
  9. import org.springframework.test.context.ContextConfiguration;
  10. /**
  11. * 配置spring和junit整合,junit启动时加载springIOC容器 spring-test,junit
  12. */
  13. // 告诉junit spring配置文件
  14. "classpath:spring/spring-dao.xml", public package com.soecode.lyf.dao;
  15. import org.junit.Test;
  16. import com.soecode.lyf.BaseTest;
  17. public @Autowired
  18. @Test
  19. void throws Exception {
  20. 1000;
  21. Book book = bookDao.queryById(bookId);
  22. System.out.println(book);
  23. }
  24. public testQueryAll () 0, for (Book book : books) {
  25. System.out.println(book);
  26. }
  27. }
  28. public testReduceNumber () long bookId = int update = bookDao.reduceNumber(bookId);
  29. System.out.println( package com.soecode.lyf.dao;
  30. import org.springframework.beans.factory.annotation.Autowired;
  31. import com.soecode.lyf.entity.Appointment;
  32. class AppointmentDaoTest extends BaseTest {
  33. private AppointmentDao appointmentDao;
  34. public testInsertAppointment () long bookId = long studentId = int insert = appointmentDao.insertAppointment(bookId, studentId);
  35. System.out.println( @Test
  36. void throws Exception {
  37. 1000;
  38. 12345678910 L;
  39. Appointment appointment = appointmentDao.queryByKeyWithBook(bookId, studentId);
  40. System.out.println(appointment);
  41. System.out.println(appointment.getBook());
  42. }
  43. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
AppointmentDaoTest测试结果

testInsertAppointment 
testInsertAppointment

testQueryByKeyWithBook 
testQueryByKeyWithBook


嗯,到这里一切到很顺利~那么我们继续service层的编码吧~可能下面开始信息里比较大,大家要做好心理准备~

首先,在写我们的业务之前,我们先定义几个预约图书操作返回码的数据字典,我们这类使用枚举类,没听过的小伙伴要好好恶补一下了(我也是最近才学到的= =)

预约业务操作返回码说明

返回码说明
1预约成功
0库存不足
-1重复预约
-2系统异常

新建一个包叫enums,在里面新建一个枚举类AppointStateEnum.java,用来定义预约业务的数据字典,没听懂没关系,我们直接看代码吧~是不是感觉有模有样了!

AppointStateEnum.java

  1. /**
  2. * 使用枚举表述常量数据字典
  3. */
  4. enum AppointStateEnum {
  5. SUCCESS( "预约成功"), NO_NUMBER( "库存不足"), REPEAT_APPOINT(- "重复预约"), INNER_ERROR(- "系统异常");
  6. int state;
  7. private int state, String stateInfo) {
  8. this.stateInfo = stateInfo;
  9. }
  10. int return state;
  11. }
  12. getStateInfo () {
  13. public stateOf ( for (AppointStateEnum state : values()) {
  14. return state;
  15. }
  16. }
  17. null;
  18. }
  19. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

接下来,在dto包下新建AppointExecution.java用来存储我们执行预约操作的返回结果。

AppointExecution.java

  1. import com.soecode.lyf.entity.Appointment;
  2. /**
  3. * 封装预约执行后结果
  4. */
  5. class AppointExecution {
  6. private // 秒杀预约结果状态
  7. int state;
  8. private String stateInfo;
  9. private Appointment appointment;
  10. AppointExecution () {
  11. }
  12. public long bookId, AppointStateEnum stateEnum) {
  13. this.state = stateEnum.getState();
  14. // 预约成功的构造器
  15. AppointExecution ( this.bookId = bookId;
  16. this.stateInfo = stateEnum.getStateInfo();
  17. // 省略getter和setter方法,toString方法
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

咱们终于可以编写业务代码了,在service包下新建BookService.java图书业务接口。

BookService.java

  1. import java.util.List;
  2. import com.soecode.lyf.entity.Book;
  3. public /**
  4. * 查询一本图书
  5. *
  6. * @param bookId
  7. * @return
  8. */
  9. Book getById( /**
  10. * 查询所有图书
  11. *
  12. * @return
  13. */
  14. List<Book> getList();
  15. long bookId, package com.soecode.lyf.service.impl;
  16. import org.slf4j.Logger;
  17. import org.springframework.beans.factory.annotation.Autowired;
  18. import org.springframework.transaction.annotation.Transactional;
  19. import com.soecode.lyf.dao.BookDao;
  20. import com.soecode.lyf.entity.Appointment;
  21. import com.soecode.lyf.enums.AppointStateEnum;
  22. @Service
  23. class BookServiceImpl implements BookService {
  24. this.getClass());
  25. @Autowired
  26. @Autowired
  27. @Override
  28. getById ( return bookDao.queryById(bookId);
  29. }
  30. public List<Book> return bookDao.queryAll( 1000);
  31. }
  32. @Transactional
  33. public AppointExecution long bookId, try {
  34. int update = bookDao.reduceNumber(bookId);
  35. 0) { return else {
  36. int insert = appointmentDao.insertAppointment(bookId, studentId);
  37. 0) { return else { return catch (Exception e) {
  38. logger.error(e.getMessage(), e);
  39. return package com.soecode.lyf.service.impl;
  40. static org.junit.Assert.fail;
  41. import org.springframework.beans.factory.annotation.Autowired;
  42. import com.soecode.lyf.dto.AppointExecution;
  43. public @Autowired
  44. @Test
  45. void throws Exception {
  46. 1001;
  47. 12345678910 L;
  48. AppointExecution execution = bookService.appoint(bookId, studentId);
  49. System.out.println(execution);
  50. }
  51. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
BookServiceImplTest测试结果

testAppoint 
testAppoint

首次执行是“预约成功”,如果再次执行的话,应该会出现“重复预约”,哈哈,我们所有的后台代码都通过单元测试啦~~是不是很开心~


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

Result.java

  1. /**
  2. * 封装json对象,所有返回结果都使用它
  3. */
  4. class Result<T> {
  5. boolean success; private T data; private String error; public // 成功时的构造器
  6. Result ( this.success = success;
  7. // 错误时的构造器
  8. Result ( this.success = success;
  9. // 省略getter和setter方法
  10. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

最后,我们写web层,也就是controller,我们在web包下新建BookController.java文件。

BookController.java

  1. import java.util.List;
  2. import org.slf4j.Logger;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.ResponseBody;
  7. import com.soecode.lyf.dto.Result;
  8. import com.soecode.lyf.service.BookService;
  9. @RequestMapping( // url:/模块/资源/{id}/细分 /seckill/list
  10. class BookController {
  11. this.getClass());
  12. private BookService bookService;
  13. "/list", method = RequestMethod.GET)
  14. list (Model model) {
  15. List<Book> list = bookService.getList();
  16. model.addAttribute( // list.jsp + model = ModelAndView
  17. "list"; // ajax json
  18. "/{bookId}/detail", method = RequestMethod.GET)
  19. private String PathVariable ("bookId") Long bookId, Model model) {
  20. null) {
  21. "redirect:/book/list";
  22. }
  23. Book book = bookService.getById(bookId);
  24. null) {
  25. "forward:/book/list";
  26. }
  27. model.addAttribute( return @RequestMapping(value = "application/json; charset=utf-8" })
  28. appoint (@ Param ("studentId") Long studentId) {
  29. null || studentId.equals( return false, return true, execution);
  30. }
  31. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64

因为我比较懒,所以我们就不测试controller了,好讨厌写前端,呜呜呜~

到此,我们的SSM框架整合配置,与应用实例部分已经结束了,我把所有源码和jar包一起打包放在了我的GitHub上,需要的可以去下载,喜欢就给个star吧,这篇东西写了两个晚上也不容易啊。

源码下载:http://github.com/liyifeng1994/ssm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值