下面这篇文章主要给大家介绍了关于整合SSM框架:Spring MVC + Spring + MyBatis的相关资料,需要的朋友可以参考下。
前言SSM(Spring+SpringMVC+Mybatis)是目前较为主流的企业级架构方案,不知道大家有没有留意,在我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能;而且在大部分教学课堂中,也会把SSH作为最核心的教学内容。但是,我们在实际应用中发现,SpringMVC可以完全替代Struts,配合注解的方式,编程非常快捷,而且通过restful风格定义url,让地址看起来非常优雅。另外,MyBatis也可以替换Hibernate,正因为MyBatis的半自动特点,我们程序猿可以完全掌控SQL,这会让有数据库经验的程序猿能开发出高效率的SQL语句,而且XML配置管理起来也非常方便。好了,如果你也认同我的看法,那么下面我们一起来做整合吧!话不多说,来一起看看详细的介绍:在写代码之前我们先了解一下这三个框架分别是干什么的?相信大以前也看过不少这些概念,我这就用大白话来讲,如果之前有了解过可以跳过这一大段,直接看代码!SpringMVC:它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只反馈josn/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!!Spring:太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。MyBatis:如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦捂脸)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。SSM框架整合配置好了,前面bb那么多,下面我们真正开始敲代码了首先我们打开IED,我这里用的是eclipse(你们应该也是用的这个,对吗?),创建一个动态web项目,建立好相应的目录结构(重点!)(打了马赛克是因为这里还用不到,你们不要那么污好不好?)我说一下每个目录都有什么用吧(第一次画表格,我发现markdown的表格语法很不友好呀)这个目录结构同时也遵循maven的目录规范~resources 没什么好说的,好像也很少用到,但这个是maven的规范。我先新建好几个必要的包,并为大家讲解一下每个包的作用,顺便理清一下后台的思路还有最后一步基础工作,导入我们相应的jar包,我使用的是maven来管理我们的jar,所以只需要在poom.xml中加入相应的依赖就好了,如果不使用maven的可以自己去官网下载相应的jar,放到项目WEB-INF/lib目录下。关于maven的学习大家可以看慕课网的视频教程,这里就不展开了。我把项目用到的jar都写在下面,版本都不是最新的,大家有经验的话可以自己调整版本号。另外,所有jar都会与项目一起打包放到我的github上,喜欢的给个star吧poom.xml4.0.0com.soecode.ssmssmwar0.0.1-SNAPSHOTssm Maven Webapphttp://github.com/liyifeng1994/ssm junitjunit4.11 ch.qos.logbacklogback-classic1.1.1 mysqlmysql-connector-java5.1.37runtimec3p0c3p00.9.1.2 org.mybatismybatis3.3.0org.mybatismybatis-spring1.2.3 taglibsstandard1.1.2jstljstl1.2com.fasterxml.jackson.corejackson-databind2.5.4javax.servletjavax.servlet-api3.1.0 org.springframeworkspring-core4.1.7.RELEASEorg.springframeworkspring-beans4.1.7.RELEASEorg.springframeworkspring-context4.1.7.RELEASE org.springframeworkspring-jdbc4.1.7.RELEASEorg.springframeworkspring-tx4.1.7.RELEASE org.springframeworkspring-web4.1.7.RELEASEorg.springframeworkspring-webmvc4.1.7.RELEASE org.springframeworkspring-test4.1.7.RELEASE redis.clientsjedis2.7.3com.dyuproject.protostuffprotostuff-core1.0.8com.dyuproject.protostuffprotostuff-runtime1.0.8 commons-collectionscommons-collections3.2ssm下面真的要开始进行编码工作了,坚持到这里辛苦大家了~第一步:我们先在spring文件夹里新建spring-dao.xml文件,因为spring的配置太多,我们这里分三层,分别是dao service web。1、读入数据库连接相关参数(可选)2、配置数据连接池配置连接属性,可以不读配置项文件直接在这里写死配置c3p0,只配了几个常用的3、配置SqlSessionFactory对象(mybatis)4、扫描dao层接口,动态实现dao接口,也就是说不需要daoImpl,sql和参数都写在xml文件上spring-dao.xmlbook
(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=1000 DEFAULT CHARSET=utf8 COMMENT=‘图书表’-- 初始化图书数据INSERT INTO book
(book_id
, name
, number
)VALUES(1000, ‘Java程序设计’, 10),(1001, ‘数据结构’, 10),(1002, ‘设计模式’, 10),(1003, ‘编译原理’, 10)-- 创建预约图书表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
),INDEX idx_appoint_time
(appoint_time
)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='预约图书表’在entity包中添加两个对应的实体,图书实体Book.java和预约图书实体Appointment.java。Book.javapackage com.soecode.lyf.entity;public class Book {private long bookId;// 图书IDprivate String name;// 图书名称private int number;// 馆藏数量// 省略构造方法,getter和setter方法,toString方法}Appointment.javapackage com.soecode.lyf.entity;import java.util.Date;/** 预约图书实体*/public class Appointment {private long bookId;// 图书IDprivate long studentId;// 学号private Date appointTime;// 预约时间// 多对一的复合属性private Book book;// 图书实体// 省略构造方法,getter和setter方法,toString方法}在dao包新建接口BookDao.java和Appointment.javaBookDao.javapackage com.soecode.lyf.dao;import java.util.List;import com.soecode.lyf.entity.Book;public interface BookDao {/*** 通过ID查询单本图书** @param id* @return*/Book queryById(long id);/*** 查询所有图书** @param offset 查询起始位置* @param limit 查询条数* @return*/List queryAll(@Param(“offset”) int offset, @Param(“limit”) int limit);/*** 减少馆藏数量** @param bookId* @return 如果影响行数等于>1,表示更新的记录行数*/int reduceNumber(long bookId);}AppointmentDao.javapackage com.soecode.lyf.dao;import org.apache.ibatis.annotations.Param;import com.soecode.lyf.entity.Appointment;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接口不用编写daoImpl, mybatis会给我们动态实现,但是我们需要编写相应的mapper。在mapper目录里新建两个文件BookDao.xml和AppointmentDao.xml,分别对应上面两个dao接口,代码如下。BookDao.xml SELECTbook_id,name,numberFROMbookWHEREbook_id = #{bookId}SELECTbook_id,name,numberFROMbookORDER BYbook_idLIMIT #{offset}, #{limit}UPDATE bookSET number = number - 1WHEREbook_id = #{bookId}AND number > 0AppointmentDao.xml INSERT ignore INTO appointment (book_id, student_id)VALUES (#{bookId}, #{studentId}) SELECTa.book_id,a.student_id,a.appoint_time,b.book_id “book.book_id”,b.name
“book.name”,b.number “book.number"FROMappointment aINNER JOIN book b ON a.book_id = b.book_idWHEREa.book_id = #{bookId}AND a.student_id = #{studentId}mapper总结:namespace是该xml对应的接口全名,select和update中的id对应方法名,resultType是返回值类型,parameterType是参数类型(这个其实可选),最后#{…}中填写的是方法的参数,看懂了是不是很简单!!我也这么觉得~ 还有一个小技巧要交给大家,就是在返回Appointment对象包含了一个属性名为book的Book对象,那么可以使用"book.属性名"的方式来取值,看上面queryByKeyWithBook方法的sql。dao层写完了,接下来test对应的package写我们测试方法吧。因为我们之后会写很多测试方法,在测试前需要让程序读入spring-dao和mybatis等配置文件,所以我这里就抽离出来一个BaseTest类,只要是测试方法就继承它,这样那些繁琐的重复的代码就不用写那么多了~BaseTest.javapackage com.soecode.lyf;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 {}因为spring-service在service层的测试中会时候到,这里也一起引入算了!新建BookDaoTest.java和AppointmentDaoTest.java两个dao测试文件。BookDaoTest.javapackage com.soecode.lyf.dao;import java.util.List;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import com.soecode.lyf.BaseTest;import com.soecode.lyf.entity.Book;public class BookDaoTest extends BaseTest {@Autowiredprivate BookDao bookDao;@Testpublic void testQueryById() throws Exception {long bookId = 1000;Book book = bookDao.queryById(bookId);System.out.println(book);}@Testpublic void testQueryAll() throws Exception {List books = bookDao.queryAll(0, 4);for (Book book : books) {System.out.println(book);}}@Testpublic void testReduceNumber() throws Exception {long bookId = 1000;int update = bookDao.reduceNumber(bookId);System.out.println(“update=” + update);}}BookDaoTest测试结果AppointmentDaoTest.javapackage com.soecode.lyf.dao;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import com.soecode.lyf.BaseTest;import com.soecode.lyf.entity.Appointment;public class AppointmentDaoTest extends BaseTest {@Autowiredprivate AppointmentDao appointmentDao;@Testpublic void testInsertAppointment() throws Exception {long bookId = 1000;long studentId = 12345678910L;int insert = appointmentDao.insertAppointment(bookId, studentId);System.out.println(“insert=” + insert);}@Testpublic 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());}}AppointmentDaoTest测试结果testInsertAppointment嗯,到这里一切到很顺利那么我们继续service层的编码吧可能下面开始信息里比较大,大家要做好心理准备~首先,在写我们的控制器之前,我们先定义几个预约图书操作返回码的数据字典,也就是我们要返回给客户端的信息。我们这类使用枚举类,没听过的小伙伴要好好恶补一下了(我也是最近才学到的= =)预约业务操作返回码说明新建一个包叫enums,在里面新建一个枚举类AppointStateEnum.java,用来定义预约业务的数据字典,没听懂没关系,我们直接看代码吧~是不是感觉有模有样了!AppointStateEnum.javapackage com.soecode.lyf.enums;/*** 使用枚举表述常量数据字典*/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.javapackage com.soecode.lyf.dto;import com.soecode.lyf.entity.Appointment;import com.soecode.lyf.enums.AppointStateEnum;/*** 封装预约执行后结果*/public class AppointExecution {// 图书IDprivate 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.javaRepeatAppointException.javaAppointException.java预约业务异常类(都需要继承RuntimeException),分别是无库存异常、重复预约异常、预约未知错误异常,用于业务层非成功情况下的返回(即成功返回结果,失败抛出异常)。NoNumberException.javapackage com.soecode.lyf.exception;/*** 库存不足异常*/public class NoNumberException extends RuntimeException {public NoNumberException(String message) {super(message);}public NoNumberException(String message, Throwable cause) {super(message, cause);}}RepeatAppointException.javapackage com.soecode.lyf.exception;/*** 重复预约异常*/public class RepeatAppointException extends RuntimeException {public RepeatAppointException(String message) {super(message);}public RepeatAppointException(String message, Throwable cause) {super(message, cause);}}AppointException.javapackage com.soecode.lyf.exception;/*** 预约业务异常*/public class AppointException extends RuntimeException {public AppointException(String message) {super(message);}public AppointException(String message, Throwable cause) {super(message, cause);}}咱们终于可以编写业务代码了,在service包下新建BookService.java图书业务接口。BookService.java2345678910111213141516171819202122232425262728293031323334353637package com.soecode.lyf.service;import java.util.List;import com.soecode.lyf.dto.AppointExecution;import com.soecode.lyf.entity.Book;/*** 业务接口:站在"使用者"角度设计接口 三个方面:方法定义粒度,参数,返回类型(return 类型/异常)/public interface BookService {/** 查询一本图书** @param bookId* @return*/Book getById(long bookId);/*** 查询所有图书** @return*/List getList();/*** 预约图书** @param bookId* @param studentId* @return*/AppointExecution appoint(long bookId, long studentId);}在service.impl包下新建BookServiceImpl.java使用BookService接口,并实现里面的方法。BookServiceImplpackage com.soecode.lyf.service.impl;import java.util.List;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 com.soecode.lyf.dao.AppointmentDao;import com.soecode.lyf.dao.BookDao;import com.soecode.lyf.dto.AppointExecution;import com.soecode.lyf.entity.Appointment;import com.soecode.lyf.entity.Book;import com.soecode.lyf.enums.AppointStateEnum;import com.soecode.lyf.exception.AppointException;import com.soecode.lyf.exception.NoNumberException;import com.soecode.lyf.exception.RepeatAppointException;import com.soecode.lyf.service.BookService;@Servicepublic class BookServiceImpl implements BookService {private Logger logger = LoggerFactory.getLogger(this.getClass());// 注入Service依赖@Autowiredprivate BookDao bookDao;@Autowiredprivate AppointmentDao appointmentDao;@Overridepublic Book getById(long bookId) {return bookDao.queryById(bookId);}@Overridepublic List 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 e1) {throw e1;} catch (RepeatAppointException e2) {throw e2;} catch (Exception e) {logger.error(e.getMessage(), e);// 所有编译期异常转换为运行期异常//return new AppointExecution(bookId, AppointStateEnum.INNER_ERROR);//错误写法throw new AppointException(“appoint inner error:” + e.getMessage());}}}下面我们来测试一下我们的业务代码吧~因为查询图书的业务不复杂,所以这里只演示我们最重要的预约图书业务!!BookServiceImplTest.javapackage com.soecode.lyf.service.impl;import static org.junit.Assert.fail;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import com.soecode.lyf.BaseTest;import com.soecode.lyf.dto.AppointExecution;import com.soecode.lyf.service.BookService;public class BookServiceImplTest extends BaseTest {@Autowiredprivate BookService bookService;@Testpublic void testAppoint() throws Exception {long bookId = 1001;long studentId = 12345678910L;AppointExecution execution = bookService.appoint(bookId, studentId);System.out.println(execution);}}BookServiceImplTest测试结果testAppoint首次执行是“预约成功”,如果再次执行的话,应该会出现“重复预约”,哈哈,我们所有的后台代码都通过单元测试啦~~是不是很开心~咱们还需要在dto包里新建一个封装json返回结果的类Result.java,设计成泛型。Result.javapackage com.soecode.lyf.dto;/*** 封装json对象,所有返回结果都使用它*/public class Result {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层,也就是controller,我们在web包下新建BookController.java文件。BookController.java2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576package com.soecode.lyf.web;import java.util.List;import org.apache.ibatis.annotations.Param;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.soecode.lyf.dto.AppointExecution;import com.soecode.lyf.dto.Result;import com.soecode.lyf.entity.Book;import com.soecode.lyf.enums.AppointStateEnum;import com.soecode.lyf.exception.NoNumberException;import com.soecode.lyf.exception.RepeatAppointException;import com.soecode.lyf.service.BookService;@Controller@RequestMapping(”/book”) // url:/模块/资源/{id}/细分 /seckill/listpublic class BookController {private Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredprivate BookService bookService;@RequestMapping(value = “/list”, method = RequestMethod.GET)private String list(Model model) {List list = bookService.getList();model.addAttribute(“list”, list);// list.jsp + model = ModelAndViewreturn “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@RequestMapping(value = “/{bookId}/appoint”, method = RequestMethod.POST, produces = {“application/json; charset=utf-8” })@ResponseBodyprivate Result 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(true, execution);}}因为我比较懒,所以我们就不测试controller了,好讨厌写前端,呜呜呜~到此,我们的SSM框架整合配置,与应用实例部分已经结束了,我把所有源码和jar包一起打包放在了我的GitHub上,需要的可以去下载,喜欢就给个star吧,这篇东西写了两个晚上也不容易啊。补充更新修改预约业务代码,失败时抛异常,成功时才返回结果,控制层根据捕获的异常返回相应信息给客户端,而不是业务层直接返回错误结果。上面的代码已经作了修改,而且错误示范也注释保留着,之前误人子弟了,还好有位网友前几天提出质疑,我也及时做了修改。修改BookController几处错误1.detail方法不是返回json的,故不用加@ResponseBody注解2.appoint方法应该加上@ResponseBody注解3.另外studentId参数注解应该是@RequestParam4.至于controller测试,测试appoint方法可不必写jsp,用curl就行,比如curl -H “Accept: application/json; charset=utf-8” -d “studentId=1234567890” localhost:8080/book/1003/appoint