自打来了博客园就一直在看帖,学到了很多知识,打算开始记录的学习到的知识点

今天我来写个整合SpringMVC4 spring4 mybatis3&测试spring事务的教程,如果有误之处,还请批评指正。

本文是原创文章,转载请注明出处


一、准备工作:

开发环境:

  1. idea(源码文章最后会给出,不下载也一样,下边都贴出来了)
  2. MySQL 5.7
  3. Tomcat 8.5
  4. Google chrome的插件postman(发送json数据)
  5. navicat for MySQL(用MySQL命令行也行)

  本教程用到的jar包如下(源码中本文中用到所有jar都已经给出):

  Spring以及springMVC的jar包:

  

   Mybatis的jar包&mybatis兼容spring的jar以及jdbc驱动:

  

  使用的数据源源为阿里巴巴的druid,和fastjson解析json

  

  Tomcat8.5,这个一般的IDE都不用管,配置好就可以

  

  文件上传下载的支持,本教程中没有写,如果有时间我会补上

  

  Mybatis-generator 自动生成Mapper和mapper.xml用的

  


二、文件结构


三、建表:

建表语句等已经存在了com.hellz.sql包中

  1. create DATABASE mybatis;
  2. use mybatis;
  3. create table teacher
  4. (
  5. tid int(10) primary key auto_increment,
  6. tname varchar(20),
  7. tusername varchar(20),
  8. tpassword varchar(15)
  9. );
  10. create table student
  11. (
  12. sid int(6) primary key auto_increment,
  13. sname varchar(20),
  14. ssex int(1),#0代表未知,1代表男,2代表女
  15. sage int(3),
  16. steacherid int(10)
  17. );
  18. insert into teacher (tname,tusername,tpassword) VALUES ('小李','username','');#其实已经设置主键自增了就不用设置tid了,这条tid=1

四、代码

Controllor包中

DemoController代码:

  1. package com.hellxz.controller;
  2.  
  3. import com.hellxz.entity.Student;
  4. import com.hellxz.entity.User;
  5. import com.hellxz.service.StudentService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.ModelMap;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.servlet.ModelAndView;
  12.  
  13. import javax.servlet.http.HttpServletRequest;
  14.  
  15. @Controller
  16. @RequestMapping("user")
  17.  
  18. public class DemoController {
  19.  
  20. // 注入studentservice
  21. @Autowired
  22. private StudentService studentService;
  23. @RequestMapping("/demo")//此处测试springmvc是否工作
  24. public String demo(){
  25. return "demo";
  26. }
  27. @RequestMapping("/mv")//此处测试modelAndView传参前端
  28. public ModelAndView modelAndView(){
  29. ModelAndView modelAndView = new ModelAndView();
  30. modelAndView.addObject("id",1);
  31. modelAndView.addObject("name","aini");
  32. modelAndView.setViewName("demo");
  33. return modelAndView;
  34. }
  35. @RequestMapping("/request")//此处测试request传参到服务端
  36. public String request(HttpServletRequest request){
  37. String id = request.getParameter("id");
  38. String name = request.getParameter("name");
  39. return "demo";//在此处打断点测试传参是否成功
  40. }
  41. @RequestMapping("/modelmap")//此处测试modelmap传参给页面
  42. public String modelMap(ModelMap modelMap){
  43. //给demo.jsp传参
  44. User u = new User();
  45. u.setId(1);
  46. u.setName("xiaomingming");
  47. modelMap.addAttribute("user",u);
  48. return "demo";
  49. }
  50.  
  51. /**
  52. * 此处用于测试json传值
  53. * 我在studentServiceImpl中把这个方法插入了一个teacher
  54. * 为了验证事务出错的回滚,如果之前teacher表中没有数据则不会回滚
  55. */
  56. @RequestMapping("/json")
  57. public String json(@RequestBody Student student){
  58. studentService.createStudent(student);//此处打断点debug查看student是否传入
  59. return "demo";
  60. }
  61.  
  62. }

dao包里的使用mybatis-generator直接生成,一会讲。


Entity包中

Student类:

  1. package com.hellxz.entity;
  2.  
  3. public class Student {
  4. private Integer sid;
  5.  
  6. private String sname;
  7.  
  8. private Integer ssex;
  9.  
  10. private Integer sage;
  11.  
  12. private Integer steacherid;
  13.  
  14. private Teacher teacher;
  15.  
  16. public Teacher getTeacher() {
  17. return teacher;
  18. }
  19.  
  20. public void setTeacher(Teacher teacher) {
  21. this.teacher = teacher;
  22. }
  23.  
  24. public Integer getSid() {
  25. return sid;
  26. }
  27.  
  28. public void setSid(Integer sid) {
  29. this.sid = sid;
  30. }
  31.  
  32. public String getSname() {
  33. return sname;
  34. }
  35.  
  36. public void setSname(String sname) {
  37. this.sname = sname == null ? null : sname.trim();
  38. }
  39.  
  40. public Integer getSsex() {
  41. return ssex;
  42. }
  43.  
  44. public void setSsex(Integer ssex) {
  45. this.ssex = ssex;
  46. }
  47.  
  48. public Integer getSage() {
  49. return sage;
  50. }
  51.  
  52. public void setSage(Integer sage) {
  53. this.sage = sage;
  54. }
  55.  
  56. public Integer getSteacherid() {
  57. return steacherid;
  58. }
  59.  
  60. public void setSteacherid(Integer steacherid) {
  61. this.steacherid = steacherid;
  62. }
  63. }

teacher类:

  1. package com.hellxz.entity;
  2.  
  3. import java.util.List;
  4.  
  5. public class Teacher {
  6. private Integer tid;
  7.  
  8. private String tname;
  9.  
  10. private String tusername;
  11.  
  12. private String tpassword;
  13.  
  14. private List<Student> student;
  15.  
  16. public List<Student> getStudents() {
  17. return student;
  18. }
  19.  
  20. public void setStudents(List<Student> students) {
  21. this.student = students;
  22. }
  23.  
  24. public Integer getTid() {
  25. return tid;
  26. }
  27.  
  28. public void setTid(Integer tid) {
  29. this.tid = tid;
  30. }
  31.  
  32. public String getTname() {
  33. return tname;
  34. }
  35.  
  36. public void setTname(String tname) {
  37. this.tname = tname == null ? null : tname.trim();
  38. }
  39.  
  40. public String getTusername() {
  41. return tusername;
  42. }
  43.  
  44. public void setTusername(String tusername) {
  45. this.tusername = tusername == null ? null : tusername.trim();
  46. }
  47.  
  48. public String getTpassword() {
  49. return tpassword;
  50. }
  51.  
  52. public void setTpassword(String tpassword) {
  53. this.tpassword = tpassword == null ? null : tpassword.trim();
  54. }
  55. }
  1. User类:
  1. package com.hellxz.entity;
  2.  
  3. /**
  4. * Created by HELLXZ on 2017/8/2.
  5. */
  6. public class User {
  7. private int id;
  8. private String name;
  9.  
  10. public int getId() {
  11. return id;
  12. }
  13.  
  14. public void setId(int id) {
  15. this.id = id;
  16. }
  17.  
  18. public String getName() {
  19. return name;
  20. }
  21.  
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. }
  1.  

  1.  
  1. Interceor包中
  1. Interceptor类:
  1. package com.hellxz.interceptor;
  2.  
  3. import org.springframework.web.servlet.HandlerInterceptor;
  4. import org.springframework.web.servlet.ModelAndView;
  5.  
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. /**
  10. * Created by HELLXZ on 2017/8/3.
  11. */
  12. public class Interceptor implements HandlerInterceptor{
  13. @Override
  14. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  15. return true;
  16. }
  17.  
  18. @Override
  19. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  20. System.out.println("方法执行了");
  21. }
  22.  
  23. @Override
  24. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  25. System.out.println("方法结束了");
  26. }
  27. }
  1.  

  1. resource包中
  1. jdbc.properties代码:
  1. jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false
  2. jdbc.username=root
  3. jdbc.password=root
  4. validationQuery=select 1
  1. spring-config.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  15. <!--开启包扫描-->
  16. <context:component-scan base-package="com.hellxz.*.**"/>
  17. <!--开启注解支持-->
  18. <context:annotation-config/>
  19. <!--开启切面支持-->
  20. <aop:aspectj-autoproxy proxy-target-class="true"/>
  21.  
  22. <!--定位jdbc.properties 配置文件-->
  23. <context:property-placeholder location="classpath:com/hellxz/resource/jdbc.properties"/>
  24. <!--创建sqlSessionFactory并指定dataSource & *mapper.xml的路径-->
  25. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  26. <property name="dataSource" ref="dataSource"/>
  27. <property name="mapperLocations" value="classpath:com/hellxz/dao/**.xml"/>
  28. </bean>
  29. <!--mybatis加载Mapper扫描配置器,指定Mapper类的包,不能用classpath:来指定!!-->
  30. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  31. <property name="basePackage" value="com.hellxz.dao"/>
  32. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  33. </bean>
  34. <!--开启spring事务支持-->
  35. <tx:annotation-driven transaction-manager="transactionManager"/>
  36. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  37. <property name="dataSource" ref="dataSource"/>
  38. </bean>
  39. <!--使用阿里巴巴的druid数据源, 别的数据源请另行参考-->
  40. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  41. <property name="url" value="${jdbc.url}"/>
  42. <property name="username" value="${jdbc.username}"/>
  43. <property name="password" value="${jdbc.password}"/>
  44.  
  45. <property name="initialSize" value="5"/>
  46. <property name="minIdle" value="0"/>
  47. <property name="validationQuery" value="${validationQuery}"/>
  48. <property name="maxActive" value="20"/>
  49. <property name="maxWait" value="6000"/>
  50. <property name="removeAbandoned" value="true"/>
  51. <property name="removeAbandonedTimeout" value="1800"/>
  52. </bean>
  53.  
  54. </beans>
  1. Spring-mvc.xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation=" http://www.springframework.org/schema/mvc
  7. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  10. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  11.  
  12. <context:component-scan base-package="com.hellxz.**"/>
  13.  
  14. <!--开启包扫描-->
  15. <context:component-scan base-package="com.hellxz.**">
  16. <!--作为spring的子容器,springMVC不具有事务能力,即无法处理@service注解的事务rollback操作-->
  17. <!--如果在同一事务下的两个操作,其中有一条错误,那么理应受spring事务管理,一起rollback-->
  18. <!--如果仅仅写为<context:component-scan base-package="com.hellxz.**"/>-->
  19. <!--spring作为父容器会失去处理事务的能力,相当于被springMVC抢了-->
  20. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
  21. </context:component-scan>
  22. <!--使用fastjson解析json数据,需要注意的是一定要写在<mvc:annotation-driven前,否则失去解析作用-->
  23. <mvc:annotation-driven>
  24. <mvc:message-converters>
  25. <bean id="jsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  26. <property name="supportedMediaTypes">
  27. <list>
  28. <value>text/html;charset=utf-8</value>
  29. <value>application/json;charset=utf-8</value>
  30. </list>
  31. </property>
  32. </bean>
  33. </mvc:message-converters>
  34. </mvc:annotation-driven>
  35. <!--开启MVC注解支持-->
  36. <mvc:annotation-driven/>
  37. <!--加载上下文注解配置-->
  38. <context:annotation-config/>
  39. <!--指明springmvc拦截器位置-->
  40. <mvc:interceptors>
  41. <!--全局拦截-->
  42. <bean id="intercepter" class="com.hellxz.interceptor.Interceptor"/>
  43. </mvc:interceptors>
  44. <!--视图解析器,controller返回的字符串在这里加上前缀&后缀,才能作为请求进入浏览器,最下方添加了jstl语句的支持-->
  45. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  46. <property name="prefix" value="/WEB-INF/view/"/>
  47. <property name="suffix" value=".jsp"/>
  48. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  49. </bean>
  50. <!--文件上传需要的设置-->
  51. <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  52. <property name="maxUploadSize" value="500000"/>
  53. <property name="maxInMemorySize" value="1024000"/>
  54. <property name="defaultEncoding" value="utf-8"/>
  55. </bean>
  56. </beans>

  1. Service包:
  1. StudentService接口:
  1. package com.hellxz.service;
  2.  
  3. import com.hellxz.dao.StudentMapper;
  4. import com.hellxz.entity.Student;
  5. import org.springframework.stereotype.Service;
  6.  
  7. /**
  8. * Created by HELLXZ on 2017/8/3.
  9. */
  10.  
  11. public interface StudentService {
  12.  
  13. int createStudent(Student student);
  14. }
  1. StudentServiceImpl类:
  1. package com.hellxz.service;
  2.  
  3. import com.hellxz.dao.StudentMapper;
  4. import com.hellxz.dao.TeacherMapper;
  5. import com.hellxz.entity.Student;
  6. import com.hellxz.entity.Teacher;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.transaction.annotation.Transactional;
  10. import com.hellxz.service.StudentService;
  11. /**
  12. * Created by HELLXZ on 2017/8/3.
  13. */
  14. @Service("studentServiceImpl")
  15. public class StudentServiceImpl implements StudentService{
  16. @Autowired
  17. private StudentMapper studentMapper;
  18. @Autowired
  19. private TeacherMapper teacherMapper;
  20. @Override
  21. @Transactional
  22. public int createStudent(Student student) {
  23. studentMapper.insertSelective(student);
  24. //后边的都是测试是否事务错误回滚,建议试一下,请先插入一条teacher数据,以确保出错!哈哈
  25. Teacher teacher = new Teacher();
  26. teacher.setTid(1);
  27. teacher.setTname("小王");
  28. teacher.setTusername("11111");
  29. teacher.setTpassword("11111");
  30. teacherMapper.insertSelective(teacher);
  31. return 0;
  32. }
  33. }
  1. TeacherService接口:
  1. package com.hellxz.service;
  2.  
  3. import com.hellxz.entity.Teacher;
  4.  
  5. /**
  6. * Created by HELLXZ on 2017/8/3.
  7. */
  8. public interface TeacherService {
  9. int createTeacher(Teacher teacher);
  10. }
  1. TeacherServiceImpl类:
  1. package com.hellxz.service;
  2.  
  3. import com.hellxz.dao.TeacherMapper;
  4. import com.hellxz.entity.Teacher;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. /**
  9. * Created by HELLXZ on 2017/8/3.
  10. */
  11. @Service("teacherServiceImpl")
  12. public class TeacherServiceImpl implements TeacherService{
  13. @Autowired
  14. private TeacherMapper teacherMapper;
  15. @Override
  16. public int createTeacher(Teacher teacher) {
  17. teacherMapper.insertSelective(teacher);
  18. return 0;
  19. }
  20. }

web.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  5. version="3.1">
  6.   <!--上下文配置定位,定位spring的配置文件,并加上监听器-->
  7. <context-param>
  8. <param-name>contextConfigLocation</param-name>
  9. <param-value>classpath:com/hellxz/resource/spring-config.xml</param-value>
  10. </context-param>
  11. <listener>
  12. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  13. </listener>
  14.   <!--springMVC的分派servlet-->
  15. <servlet>
  16. <servlet-name>ssm</servlet-name>
  17. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!--在servlet启动的时候加载springMVC的配置文件-->
  18. <init-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>classpath:com/hellxz/resource/spring-mvc.xml</param-value>
  21. </init-param>
         <!--启动顺序1,表示优先加载-->
  22. <load-on-startup>1</load-on-startup>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>ssm</servlet-name>
  26. <url-pattern>/</url-pattern>
  27. </servlet-mapping>
  28.  
  29. </web-app>

测试页面demo.jsp:

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: HELLXZ
  4. Date: 2017/8/2
  5. Time: 18:44
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <html>
  10. <head>
  11. <title>Demo</title>
  12. </head>
  13. <body>
  14. Hello !! this page named Demo<br>
  15. <%--接收modelmap--%>
  16. ${user.id}<br>
  17. ${user.name}<br>
  18. <%--接收model and view--%>
  19. ${id}<br>
  20. ${name}<br>
  21. </body>
  22. </html>

  1. 下面说一下mybatis-generator的用法,我们来生成Mapper类和Mapperxml,请确保已经建表了!!!

  1. 如图,随便找个地方新建个文件夹,把jdbc驱动还有mybatis-generatorjar包放进去
  1. 新建一个TXT,改名generatorConfig.xml,复制下面的代码,如果你要直接用在自己的项目里,请直接修改包的结构就好,很简单。
  1. generatorConfig.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
  4. <generatorConfiguration>
  5.  
  6. <!--classPathEntry:数据库的JDBC驱动 -->
  7. <classPathEntry
  8. location="G:\mybatis-generator\mysql-connector-java-5.1.34.jar" />
  9.  
  10. <context id="MysqlTables" targetRuntime="MyBatis3">
  11.  
  12. <!-- 注意这里面的顺序确定的,不能随变更改 -->
  13. <!-- 自定义的分页插件 <plugin type="com.deppon.foss.module.helloworld.shared.PaginationPlugin"/> -->
  14.  
  15. <!-- 可选的(0 or 1) -->
  16. <!-- 注释生成器 -->
  17. <commentGenerator>
  18. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  19. <property name="suppressAllComments" value="true" />
  20. </commentGenerator>
  21.  
  22. <!-- 必须的(1 required) -->
  23. <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
  24. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  25. connectionURL="jdbc:mysql://localhost:3306/mybatis"
  26. userId="root" password="root">
  27. </jdbcConnection>
  28.  
  29. <!-- 可选的(0 or 1) -->
  30. <!-- 类型转换器或者加类型解析器 -->
  31. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和
  32. NUMERIC 类型解析为java.math.BigDecimal -->
  33. <javaTypeResolver>
  34. <property name="forceBigDecimals" value="false" />
  35. </javaTypeResolver>
  36.  
  37. <!-- 必须的(1 required) -->
  38. <!-- java模型生成器 -->
  39. <!-- targetProject:自动生成代码的位置 -->
  40. <javaModelGenerator targetPackage="com.hellxz.entity"
  41. targetProject="src"
  42. >
  43. <!-- TODO enableSubPackages:是否让schema作为包的后缀 -->
  44. <property name="enableSubPackages" value="true" />
  45. <!-- 从数据库返回的值被清理前后的空格 -->
  46. <property name="trimStrings" value="true" />
  47. </javaModelGenerator>
  48.  
  49. <!-- 必须的(1 required) -->
  50. <!-- map xml 生成器 -->
  51. <sqlMapGenerator targetPackage="com.hellxz.dao"
  52. targetProject="src">
  53. <property name="enableSubPackages" value="true" />
  54. </sqlMapGenerator>
  55.  
  56. <!-- 可选的(0 or 1) -->
  57. <!-- mapper 或者就是dao接口生成器 -->
  58. <javaClientGenerator targetPackage="com.hellxz.dao"
  59. targetProject="src"
  60. type="XMLMAPPER">
  61. <property name="enableSubPackages" value="true" />
  62. </javaClientGenerator>
  63.  
  64. <!-- 必须的(1...N) -->
  65. <!-- pojo 实体生成器 -->
  66. <!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
  67. <!-- schema即为数据库名 可不写 -->
  68. <table tableName="student" domainObjectName="Student"
  69. enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
  70. enableSelectByExample="false" selectByExampleQueryId="false">
  71. <!-- 忽略字段 可选的(0 or 1) -->
  72. <!-- <ignoreColumn column="is_use" /> -->
  73. <!--//无论字段是什么类型,生成的类属性都是varchar。 可选的(0 or 1) 测试无效 -->
  74. <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> -->
  75. </table>
  76. <table tableName="teacher" domainObjectName="Teacher"
  77. enableInsert="true" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
  78. enableSelectByExample="false" selectByExampleQueryId="false">
  79. <!-- 忽略字段 可选的(0 or 1) -->
  80. <!-- <ignoreColumn column="is_use" /> -->
  81. <!--//无论字段是什么类型,生成的类属性都是varchar。 可选的(0 or 1) 测试无效 -->
  82. <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> -->
  83. </table>
  84.  
  85. </context>
  86. </generatorConfiguration>
  1. 粘贴保存,然后运行—cmd   打开命令行,cd到此文件夹,执行如下代码:
  1. java -jar mybatis-generator-core-1.3..jar -configfile generatorConfig.xml overwrite
  1. 出现successful就已经成功了,把新生成的src文件加中的两个文件夹文件按照文章开头的文件结构放进去就好。
  1.  

  1.  
  1.  配置完成,debug模式启动服务器,什么?你服务器不会配置?出门左转百度吧老兄!
  1.  

  1. 这样子就算成功了,下面进行测试

  1.  
  1. 起一个浏览器输入localhost:8080/user/demo 回车,(elipse需要在/user前加项目名,这里用idea),如果进入此界面则说明springMVC正常

  1.  
  1. 下面只需要测试Spring的事务是否正常了
  1. 我们先捋一下流程(还不会画思维导图,谅解):
  1. 发送json —-> controller解析处理封装student —-> 找到RequestMapping(”/json”)
  1. —-> 打断点查看student对象是否正确,继续,调用studentServicecreateStudent()—-> 找到studentServiceIml调用具体方法
  1. —-> 方法中调用了mybatismapper的方法,同时我们加了条坏数据插入到teacher —-> 如果两条数据都没有插进去,则说明spring事务正常,同一事务中的只要有错误就会回滚了
  1.  

  1.  
  1. 好,我们开始:
  1. 使用postmanlocalhost:8080/user/json发送如下json语句,如图
  1. 注意json用的是花括号!如果你已经给student插数据了,那么请找个没有使用的sid
  1. 可以看见已经传了个student对象进来了,先别继续,查看数据库
  1.  
  1. 我们看到student表中还是空的,这么说来,sid=1是可以插进来的,当然teacher里一定要有一条数据哦~
  1. 剩下的大家可以打断点继续跟踪,我这继续说就有点侮辱大家智商了,方法执行完毕后我们再来查看数据是否正常
  1. 不出所料,student表中并没有插入数据,事务回滚成功!
  1. 如果有疑问,比如说怀疑根本没连上mybatis,或者说本来就插不进去,那么请删除teacher表中的所有数据,再postman发一下json查看一下,囧,我已经做了,见下图
  1. Student
  1. Teacher
  1. 我们再捋一下流程:
  1. 我们使用postman发送一条jsonlocalhost:8080/user/json,
  1. 这条数据会在DemoController中进行解析,封装成一个student对象,因为我们已经注入了StudentService对象,我们把student对象传给他,因为是接口,会传给StudentServiceImpl实现类,实现类中我们先使用StudentMapper对象通过mybatis向数据库插入刚才传过来的对象,自动解析成数据插值,在刚才的方法下边我们故意弄了一条错误的teacher数据。
  1. 如果看了我写的建表SQL语句可能会好奇:为什么我要插入一条teacher数据?其实原因很简单,teacher的主键是自增的,我插入已经占用的主键的值肯定是错误的,我们要测试的是spring的事务,如果同一个事务中有多条数据进行插值,如果有一条错误我们想让它们同时完成或者同时不完成,那么这就很有用了。正常来讲,查询数据库你会发现这两条都没有插入。
  1.  
  1. 如果想试试事务失效是什么样子,请手动修改spring-mvc.xml中的代码
  1. <!--open package scanner-->
  2. <context:component-scan base-package="com.hellxz.**">
  3. <!--if you do not set this data, when you insert two transaction together and one of them is error-->
  4. <!--and you want to if correct let them all succeed or false all rollback, you must set this-->
  5. <!--you do not set unless you want one data succeed and one false-->
  6. <!--it means springmvc has no transaction power of "@Service", but Spring has it.-->
  7. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
  8. </context:component-scan>

改为:

  1. <context:component-scan base-package="com.hellxz.**"/>
  1. 好了,这就是我为大家准备的ssm教程。第一次写,写了好几个小时-_-||
    controller中还有几个测试传参的有兴趣可以试验下
  1.  
  1. 源码包就是我的项目直接拿出来的,不知道博客园有没有专门上传附件的地方,传到百度云了
    源码是我之前输入法有问题写的注释,xml注释大多用的英文的,具体请参考本贴
    链接:http://pan.baidu.com/s/1min414W
    [hide]密码:6v6s[/hide]
  1.  

                                                            第一次编辑2017-08-03 22:30:23

SSM手把手整合教程&测试事务的更多相关文章

  1. SSM简单整合教程&测试事务

    自打来了博客园就一直在看帖,学到了很多知识,打算开始记录的学习到的知识点 今天我来写个整合SpringMVC4 spring4 mybatis3&测试spring事务的教程,如果有误之处,还请 ...

  2. SSM简明教程:简单的十步教你搭建人生第一个SSM框架[ SSM框架整合教程(Spring+SpringMVC+MyBatis) ]

    SSM_BookSystem SSM框架基础 SSM_BookSystem ---> Hello CRUD 说明:本项目目前包含基础的CRUD 日期:2017-05-01 22:25:37 作者 ...

  3. 手把手整合SSM框架

    前言 如果看过前几篇文章,对 Spring 和 MyBatis 有了一定了解,一定想上手试试.这篇文章从 0 到 1,手把手整合 SSM (Spring.Spring MVC.MyBatis). 本篇 ...

  4. SSM 框架-06-详细整合教程(IDEA版)(Spring+SpringMVC+MyBatis)

    SSM 框架-06-详细整合教程(IDEA版)(Spring+SpringMVC+MyBatis) SSM(Spring.Spring MVC和Mybatis)如果你使用的是 Eclipse,请查看: ...

  5. SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis)

    SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis) 如果你使用的是 Intellij IDEA,请查看: SSM的配置流程详细的写了出来,方便很少 ...

  6. SSM框架——详细整合教程

    SSM框架——详细整合教程(Spring+SpringMVC+MyBatis) 1.基本概念   1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Jav ...

  7. SSM框架整合搭建教程

    自己配置了一个SSM框架,打算做个小网站,这里把SSM的配置流程详细的写了出来,方便很少接触这个框架的朋友使用,文中各个资源均免费提供! 一. 创建web项目(eclipse) File-->n ...

  8. SSM框架简介及整合教程

    1.Spring Spring 框架是 Java 应用最广的框架,它的成功来源于理念,而不是技术本身,它的理念包括 IoC (控制反转) 和 A面向切面编程).Spring框架是个轻量级的Java E ...

  9. SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)【申明:来源于网络】

    SSM框架--详细整合教程(Spring+SpringMVC+MyBatis)[申明:来源于网络] 地址:http://blog.csdn.net/u014662268/article/details ...

随机推荐

  1. Java订单号生成,唯一订单号(日均千万级别不重复)

    Java订单号生成,唯一订单号 相信大家都可以搜索到很多的订单的生成方式,不懂的直接百度.. 1.订单号需要具备以下几个特点. 1.1 全站唯一性. 1.2 最好可读性. 1.3 随机性,不能重复,同 ...

  2. @NotEmpty、@NotBlank、@NotNull的区别

    @NotEmpty 用在集合类上面  @NotBlank 用在String上面  @NotNull 用在基本类型上 只有简单的结果,但是再更具体一点的内容就搜不到了,所以去看了看源码,发现了如下的注释 ...

  3. bash脚本之数组学习

    在bash中可使用索引数组和关联数组,bash在4.0版本之后才添加了对关联数组的支持 一.索引数组 1.定义索引数组 # 方式1 array_value=(1 2 3 4 5 6)或者array_v ...

  4. Python day02 三元运算

     type  查看数据类型.2 **32  :2的32次方 .浮点的表示类型是小数,但是小数不仅仅包括浮点 浮点数用来处理实数,即带有小数的数字 三元运算:  result = 值1 if 条件 el ...

  5. 小白的Python之路 day5 time,datatime模块详解

    一.模块的分类 可以分成三大类: 1.标准库 2.开源模块 3.自定义模块 二.标准库模块详解 1.time与datetime 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时 ...

  6. Hibernate中关于HQL查询返回List<Object>数据的结果集问题

    ---恢复内容开始--- 开发中遇到的一个小问题,使用Hibernate中的HQL查询时,使用query.list()查询出来的是一个List<Object>结果集 原来代码: publi ...

  7. Transact-SQL参考--学习笔记

    基本的就不累赘了. 运算符 除法: dividend / divisor 如果用一个整数的 divisor 去除整数的 dividend,其结果是一个整数,小数部分被截断,如果要有小数可以将divid ...

  8. 强化学习之Sarsa (时间差分学习)

    上篇文章讲到Q-learning, Sarsa与Q-learning的在决策上是完全相同的,不同之处在于学习的方式上 这次我们用openai gym的Taxi来做演示 Taxi是一个出租车的游戏,把顾 ...

  9. 申请的服务器安装tomcat后不能访问的问题

    新申请的阿里云服务器,操作系统是CentOS6.5,安装jdk1.8版本,用java -version命令可以查看jdk版本,安装正确会有版本显示.然后安装tomcat,tomcat安装后默认端口是8 ...

  10. 【矩阵快速幂】bzoj1297 [SCOI2009]迷路

    1297: [SCOI2009]迷路 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 1407  Solved: 1007[Submit][Status ...