最新ssm框架超级详细整合教程带测试(2018-10-26号更新)

最近准备用SSM框架写一个项目,于是乎在论坛上搜,发现好多博文不够全面,或者是jar包版本太久了。就打算自己搭建一个出来,其实很简单,关键就是整合的时候配置文件的配置,以及导入必须的依赖。此篇博文写得非常详细,大家可以参考学习,有疑问请留言。

一:SSM框架简介

SSM(Spring+SpringMVC+MyBatis)框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成,常作为数据源较简单的web项目的框架。

1、Spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

2、SpringMVC
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

3、MyBatis
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
PS:既然说到了Mybatis,那我就必须提一下Mybatis三剑客(mybatis-generator、mybatis-plugin、mybatis-pagehelper),Mybatis的三剑客会让你的开发变得轻巧,如鱼得水。本来我打算在把Mybatis三剑客的介绍和使用教程放进来的,斟酌过后,鉴于篇幅太长,我会再单独写一篇博文专门来介绍Mybatis三剑客。

二、SSM框架整合

**1.**首先建立maven项目,建立以后目录结构可能不完整,大家可以补充完整。maven项目建立。给大家看一下我整合好的目录结构:
这里写图片描述
2. SSM框架整合分为三部分,即Spring和Mybatis整合以及Spring和SpringMVC的整合,整合形成的的配置文件分别为spring-mybatis.xml和spring-mvc.xml。然后通过web.xml将上述两部分整合形成一个完整的SSM框架。
项目中我用到的数据库是Mysql,所以还有一个关于数据库配置信息的配置文件jdbc.properties。除此之外,我们使用Apache的开源项目Log4j来进行项目运行过程的日志信息输出,其配置文件为log4j.properties。最后还有Maven的配置文件pom.xml(Project Object Model,项目对象模型。该文件用于管理:源代码、配置文件、开发者的信息和角色、问题追踪系统、组织信息、项目授权、项目的url、项目的依赖关系等等。)

2.1 pom.xml、jdbc.properties、log4j.properties配置:
pom.xml:

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com</groupId>
	<artifactId>ssm</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>ssm Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<!-- spring版本号 -->
		<spring.version>4.2.4.RELEASE</spring.version>
		<!-- mybatis版本号 -->
		<mybatis.version>3.2.6</mybatis.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.7</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
		<!--解决用maven插件编译时产生乱码问题-->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
	</properties>

	<dependencies>
		<!-- junit单元测试 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
			<scope>test</scope>
		</dependency>
		<!-- spring核心包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- 导入java ee jar 包 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
		</dependency>
		<!-- 导入Mysql数据库链接jar包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>
		<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- JSTL标签类 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<!-- 格式化对象,方便输出日志 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.41</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- log end -->
		<!-- 映入JSON -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<!-- 上传组件包 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		<!--Mybatis三剑客之一:pagehelper分页插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.0.3</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>ssm</finalName>
		<plugins>
			<!--指定maven编译的jdk版本,如果不指定,maven3默认用jdk 1.5 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>
			<!--完美解决了编译过程中进行的单元测试中文乱码问题,为了解决乱码头都破了。头铁的可以注释掉这几行代码编译试一下中文乱码不 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
					<skip>true</skip> <!-- 编译过程中是否跳过测试 是:true 否:false -->
					<argLine>-Dfile.encoding=UTF-8</argLine>
				</configuration>
			</plugin>
			<!--我选用的是jetty插件进行项目发布的 ,跟Tomcat的区别,可自行百度 -->
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.4.11.v20180605</version>
				<configuration>
					<httpConnector>
						<port>8080</port>
					</httpConnector>
					<stopKey>shutdown</stopKey>
					<stopPort>9966</stopPort>
				</configuration>
			</plugin>
		</plugins>
		<!--<resources></resources>之间的代码解决了编译时报在XXXMapper中找不到XYZ方法的异常,在这里被打了一上午脸-->
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
	</build>
</project>

jdbc.properties :

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://cdb-nnXXX8w.bj.tencentcdb.com:10000/test
username=root
password=xyz123456
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570
initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570
maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2
maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2
minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4
maxWait=60000

PS:这里我解释一下,作为萌新可能对于这句有疑惑url=jdbc:mysql://cdb-nnXXX8w.bj.tencentcdb.com:10000/test。因为我用的是腾讯的Mysql数据库服务器,所以cdb-nnXXX8w.bj.tencentcdb.com就是数据库服务器的域名,10000是端口号。如果你的数据库是本地安装的话。那么url=jdbc:mysql://localhost:3306/数据库名。而且jdbc.properties这个配置文件有严格的空格监测,每一行的结尾不能留空格,最后一行不能有空行,不然会报错。

log4j.properties:

 log4j.rootLogger=INFO,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log  
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

log4j的配置文件网上有很多全面的信息介绍,需要更进一步了解的的可以度娘一下。

3. Spring、Mybatis整合
spring-mybatis.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:p="http://www.springframework.org/schema/p"
	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-3.1.xsd    
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- 自动扫描 -->
	<context:component-scan base-package="com.ssm" />
	<!-- 引入数据库配置文件 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<!-- 初始化连接大小 -->
		<property name="initialSize" value="${initialSize}"></property>
		<!-- 连接池最大数量 -->
		<property name="maxActive" value="${maxActive}"></property>
		<!-- 连接池最大空闲 -->
		<property name="maxIdle" value="${maxIdle}"></property>
		<!-- 连接池最小空闲 -->
		<property name="minIdle" value="${minIdle}"></property>
		<!-- 获取连接最大等待时间 -->
		<property name="maxWait" value="${maxWait}"></property>
	</bean>
	<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自动扫描mapping.xml文件 -->
		<!-- 看到这里的请注意,接下来被注释的一行是我按照项目路径配置的,但是运行起来一直报找不到XXXMapper。xml的错误最后换成再接一下来的哪个就合适了  -->
		<!-- <property name="mapperLocations" value="classpath*:com/ssm/dao/mapping/*.xml"></property> -->
		<property name="mapperLocations" value="classpath*:com/ssm/dao/**/*Mapper.xml"></property>
		<!--Mybatis三剑客之分页查询pagehelper插件配置 -->
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<!--使用下面的方式配置参数,一行配置一个 -->
						<value>
						    <!--数据库采用mysql  -->
						    helperDialect=mysql
						    <!-- 和startPage中的pageNum效果一样-->
							offsetAsPageNum=true
							<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
							rowBoundsWithCount=true
							<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
      					    <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
							pageSizeZero=true
							<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
       					    <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
							reasonable=true
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>
	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ssm.dao" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
	</bean>
	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>

PS:对于配置文件中路径疑惑的,可以翻上去看我贴出来的目录结构,参考来配置你的。

4. Spring、SpringMVC整合
spring-mvc.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:p="http://www.springframework.org/schema/p"
	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-3.1.xsd    
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
	<context:component-scan
		base-package="com.ssm.controller" />
	<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>
	<bean
		class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<property name="order" value="0" />
	</bean>
	<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
			</list>
		</property>
	</bean>
	<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 默认编码 -->
		<property name="defaultEncoding" value="utf-8" />
		<!-- 文件大小最大值 -->
		<property name="maxUploadSize" value="10485760000" />
		<!-- 内存中的最大值 -->
		<property name="maxInMemorySize" value="40960" />
	</bean>
</beans>  

5. 三大框架整合SSM
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<!-- Spring和mybatis的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml</param-value>
	</context-param>
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>
	<!-- Spring MVC servlet -->
	<servlet>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!--静态资源的映射配置 -->
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.css</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.gif</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.jpg</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>*.js</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>  

PS:至此,SSM框架整合便完成了,接下来进行测试。

三、Junit测试

1. 测试前的准备

  1. 1 数据库的设计
    为大家贴出来代码,复制可以直接运行生成对应的数据库信息。如果你的数据库有user_t这个表,运行下面代码记得改名,不然小心弄丢你的表数据
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user_t
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t`  (
  `id` int(10) NOT NULL,
  `user_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `password` varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `age` int(10) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES (1001, '曹春丽', '1234', 15);
INSERT INTO `user_t` VALUES (1002, '张三', '2552', 22);
INSERT INTO `user_t` VALUES (1003, '李四', '5852', 36);
INSERT INTO `user_t` VALUES (1004, '王五', '2263', 43);
INSERT INTO `user_t` VALUES (1005, '张伟', '5253', 22);
INSERT INTO `user_t` VALUES (1006, '张青', '4745', 15);
INSERT INTO `user_t` VALUES (1007, '李德华', '4453', 44);
INSERT INTO `user_t` VALUES (1008, '李极大', '8554', 25);
INSERT INTO `user_t` VALUES (1009, '王大声', '1553', 25);
INSERT INTO `user_t` VALUES (1010, '白一', '1525', 12);
INSERT INTO `user_t` VALUES (1011, '白二', '2552', 14);
INSERT INTO `user_t` VALUES (1012, '白三', '2585', 36);
INSERT INTO `user_t` VALUES (1013, '白四', '1155', 23);
INSERT INTO `user_t` VALUES (1014, '白五', '5775', 56);
INSERT INTO `user_t` VALUES (1015, '大白', '2526', 36);
INSERT INTO `user_t` VALUES (1016, '穆华天', '2852', 25);
INSERT INTO `user_t` VALUES (1017, '安抚', '2876', 19);
INSERT INTO `user_t` VALUES (1018, '玛顿', '2878', 15);
INSERT INTO `user_t` VALUES (1019, '苏珊', '4687', 25);
INSERT INTO `user_t` VALUES (1020, '牛顿', '2541', 78);
INSERT INTO `user_t` VALUES (1021, '拉米提', '8541', 12);
INSERT INTO `user_t` VALUES (1022, '阿达', '1434', 78);
INSERT INTO `user_t` VALUES (1023, '杨过', '4665', 65);
INSERT INTO `user_t` VALUES (1024, '苏乞儿', '2457', 57);
INSERT INTO `user_t` VALUES (1025, '亚里士多德', '0265', 85);
INSERT INTO `user_t` VALUES (1026, '奥德吉', '3635', 67);
INSERT INTO `user_t` VALUES (1027, '本拉登', '3935', 45);
INSERT INTO `user_t` VALUES (1028, '夏娃', '3855', 25);

SET FOREIGN_KEY_CHECKS = 1;
  1. 2根据user_t表结构利用Mybatis三剑客之mybatis-generator来自动生成代码。在这里我先把代码贴出来,对于Mybatis三剑客,大家可以在我的其他博文里面看详细介绍。
    这里写图片描述
    实体类User.java
package com.ssm.model;

public class User {
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

UserExample.java类:用于用户自定义sql查询
这个暂时用不到,里面的代码400+行,太多了就不贴了。

接口类:UserMapper.java

package com.ssm.dao;
import com.ssm.model.User;
import com.ssm.model.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    long countByExample(UserExample example);
    int deleteByExample(UserExample example);
    int deleteByPrimaryKey(Integer id);
    int insert(User record);
    int insertSelective(User record);
    List<User> selectByExample(UserExample example);
    User selectByPrimaryKey(Integer id);
    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
    int updateByExample(@Param("record") User record, @Param("example") UserExample example);
    int updateByPrimaryKeySelective(User record);
    int updateByPrimaryKey(User record);
}

dao层接口实现:UserMapper.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="com.ssm.dao.UserMapper">
	<resultMap id="BaseResultMap" type="com.ssm.model.User">
		<id column="id" jdbcType="INTEGER" property="id" />
		<result column="user_name" jdbcType="VARCHAR" property="userName" />
		<result column="password" jdbcType="VARCHAR" property="password" />
		<result column="age" jdbcType="INTEGER" property="age" />
	</resultMap>
	<sql id="Example_Where_Clause">
		<where>
			<foreach collection="oredCriteria" item="criteria" separator="or">
				<if test="criteria.valid">
					<trim prefix="(" prefixOverrides="and" suffix=")">
						<foreach collection="criteria.criteria" item="criterion">
							<choose>
								<when test="criterion.noValue">
									and ${criterion.condition}
								</when>
								<when test="criterion.singleValue">
									and ${criterion.condition} #{criterion.value}
								</when>
								<when test="criterion.betweenValue">
									and ${criterion.condition} #{criterion.value} and
									#{criterion.secondValue}
								</when>
								<when test="criterion.listValue">
									and ${criterion.condition}
									<foreach close=")" collection="criterion.value" item="listItem"
										open="(" separator=",">
										#{listItem}
									</foreach>
								</when>
							</choose>
						</foreach>
					</trim>
				</if>
			</foreach>
		</where>
	</sql>
	<sql id="Update_By_Example_Where_Clause">
		<where>
			<foreach collection="example.oredCriteria" item="criteria"
				separator="or">
				<if test="criteria.valid">
					<trim prefix="(" prefixOverrides="and" suffix=")">
						<foreach collection="criteria.criteria" item="criterion">
							<choose>
								<when test="criterion.noValue">
									and ${criterion.condition}
								</when>
								<when test="criterion.singleValue">
									and ${criterion.condition} #{criterion.value}
								</when>
								<when test="criterion.betweenValue">
									and ${criterion.condition} #{criterion.value} and
									#{criterion.secondValue}
								</when>
								<when test="criterion.listValue">
									and ${criterion.condition}
									<foreach close=")" collection="criterion.value" item="listItem"
										open="(" separator=",">
										#{listItem}
									</foreach>
								</when>
							</choose>
						</foreach>
					</trim>
				</if>
			</foreach>
		</where>
	</sql>
	<sql id="Base_Column_List">
		id, user_name, password, age
	</sql>
	<select id="selectByExample" parameterType="com.ssm.model.UserExample"
		resultMap="BaseResultMap">
		select
		<if test="distinct">
			distinct
		</if>
		<include refid="Base_Column_List" />
		from user_t
		<if test="_parameter != null">
			<include refid="Example_Where_Clause" />
		</if>
		<if test="orderByClause != null">
			order by ${orderByClause}
		</if>
	</select>
	<select id="selectByPrimaryKey" parameterType="java.lang.Integer"
		resultMap="BaseResultMap">
		select
		<include refid="Base_Column_List" />
		from user_t
		where id = #{id,jdbcType=INTEGER}
	</select>
	<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
		delete from user_t
		where id = #{id,jdbcType=INTEGER}
	</delete>
	<delete id="deleteByExample" parameterType="com.ssm.model.UserExample">
		delete from user_t
		<if test="_parameter != null">
			<include refid="Example_Where_Clause" />
		</if>
	</delete>
	<insert id="insert" parameterType="com.ssm.model.User">
		insert into user_t (id, user_name, password,
		age)
		values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR},
		#{password,jdbcType=VARCHAR},
		#{age,jdbcType=INTEGER})
	</insert>
	<insert id="insertSelective" parameterType="com.ssm.model.User">
		insert into user_t
		<trim prefix="(" suffix=")" suffixOverrides=",">
			<if test="id != null">
				id,
			</if>
			<if test="userName != null">
				user_name,
			</if>
			<if test="password != null">
				password,
			</if>
			<if test="age != null">
				age,
			</if>
		</trim>
		<trim prefix="values (" suffix=")" suffixOverrides=",">
			<if test="id != null">
				#{id,jdbcType=INTEGER},
			</if>
			<if test="userName != null">
				#{userName,jdbcType=VARCHAR},
			</if>
			<if test="password != null">
				#{password,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				#{age,jdbcType=INTEGER},
			</if>
		</trim>
	</insert>
	<select id="countByExample" parameterType="com.ssm.model.UserExample"
		resultType="java.lang.Long">
		select count(*) from user_t
		<if test="_parameter != null">
			<include refid="Example_Where_Clause" />
		</if>
	</select>
	<update id="updateByExampleSelective" parameterType="map">
		update user_t
		<set>
			<if test="record.id != null">
				id = #{record.id,jdbcType=INTEGER},
			</if>
			<if test="record.userName != null">
				user_name = #{record.userName,jdbcType=VARCHAR},
			</if>
			<if test="record.password != null">
				password = #{record.password,jdbcType=VARCHAR},
			</if>
			<if test="record.age != null">
				age = #{record.age,jdbcType=INTEGER},
			</if>
		</set>
		<if test="_parameter != null">
			<include refid="Update_By_Example_Where_Clause" />
		</if>
	</update>
	<update id="updateByExample" parameterType="map">
		update user_t
		set id = #{record.id,jdbcType=INTEGER},
		user_name = #{record.userName,jdbcType=VARCHAR},
		password = #{record.password,jdbcType=VARCHAR},
		age = #{record.age,jdbcType=INTEGER}
		<if test="_parameter != null">
			<include refid="Update_By_Example_Where_Clause" />
		</if>
	</update>
	<update id="updateByPrimaryKeySelective" parameterType="com.ssm.model.User">
		update user_t
		<set>
			<if test="userName != null">
				user_name = #{userName,jdbcType=VARCHAR},
			</if>
			<if test="password != null">
				password = #{password,jdbcType=VARCHAR},
			</if>
			<if test="age != null">
				age = #{age,jdbcType=INTEGER},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>
	<update id="updateByPrimaryKey" parameterType="com.ssm.model.User">
		update user_t
		set user_name = #{userName,jdbcType=VARCHAR},
		password = #{password,jdbcType=VARCHAR},
		age = #{age,jdbcType=INTEGER}
		where id = #{id,jdbcType=INTEGER}
	</update>
</mapper>

类UserService.java

package com.ssm.service;

import java.util.List;

import com.ssm.model.User;
import com.ssm.model.UserExample;

public interface UserService {  
		    public User getUserById(int userId); 		   
}

service层接口实现UserServiceImpl.java :

package com.ssm.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.dao.UserMapper;
import com.ssm.model.User;
import com.ssm.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Resource
	@Autowired
	private UserMapper userMapper;
	public User getUserById(int userId) {
		// TODO Auto-generated method stub
		return this.userMapper.selectByPrimaryKey(userId);
	}	
}

编写测试类(测试Spring、Mybatis的整合是否成功)

package com.ssm.test;
import javax.annotation.Resource;
import org.apache.log4j.Logger;  
import org.junit.Test;  
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.ssm.model.User;
import com.ssm.service.UserService;  
@RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类  
@ContextConfiguration(locations = {"classpath*:spring-mybatis.xml"})  
public class TestMyBatis {  
   private static Logger logger = Logger.getLogger(TestMyBatis.class);  
   @Resource 
   @Autowired
   private UserService userService=null;  
   @Test  
   public void test1() {  
       User user = userService.getUserById(1001);  //1001在数据库有对应的数据
       logger.info(JSON.toJSONString(user));  
   }  
}  

编写测试类(测试Spring、SpringMVC的整合是否成功)

package com.ssm.controller;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ssm.model.User;

@Controller
@RequestMapping("/user")
// /user/**
public class TestController {
	private static Logger log = LoggerFactory.getLogger(TestController.class);
	// /user/test?id=1001
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String test(HttpServletRequest request, Model model) {
		int userId = Integer.parseInt(request.getParameter("id"));
		System.out.println("userId:" + userId);
		return "usertest";
	}
}

编写测试类(测试SSM框架整合是否成功)

package com.ssm.controller;
import javax.servlet.http.HttpServletRequest;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.model.User;
import com.ssm.service.UserService;

@Controller
@RequestMapping("/user1")
// /user/**
public class TestController {
	private static Logger log = LoggerFactory.getLogger(TestController.class);
	// /user1/test1?id=1001
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/test1", method = RequestMethod.GET)
	public @ResponseBody User test(HttpServletRequest request, Model model) {
		ModelAndView modelAndView = new ModelAndView();
		int userId = Integer.parseInt(request.getParameter("id"));
		User user = userService.getUserById(userId);
		modelAndView.addObject("user", user);
		return user;
	}
}

2.Spring、Mybatis整合测试
这里写图片描述
PS:Spring、Mybatis整合成功
3.Spring、SpringMVC整合测试
这里写图片描述
PS:Spring、SpringMVC整合成功

4. SSM项目综合测试
这里写图片描述
到此,SSM项目整合结束,只有经历了你才会发现你看起来很简单的东西操作起来并非如此。比如:jar包版本不合适,配置文件路径访问不到等等,你竟然会发现,除过你以前见过的404,500http请求失败的错误,他的家族还有400、401、402、403、405、406、407、412、414、501、502这么多,由于是新手,我就碰到了好几个,刷新了菜鸟的认识观。不过,互联网真的是一个好东西,至少作为一个菜鸟,你遇到的问题都是别人遇到过的。所以你遇到的问题都不是问题,遇到了就去度娘那里找答案吧。

SSM框架整合和测试源代码下载##

##基于SSM框架利用Pagehelper插件实现的物理分页查询源代码(包含上述所有代码)##
Mybatis三剑客之Mybatis generator 自动生成代码插件的安装及使用方法详解
Mybatis三剑客之Mybatis pagehelper 分页查询插件的安装及使用方法详解

想要更多的了解或者自学SSM框架的,可以点击此链接下载SSM框架的高清PDF电子书,目录如下图所示

这里写图片描述


就怕你一生碌碌无为,还安慰自己平凡可贵
by13213

  • 2
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值