一个从零开始的SSM框架Demo对一个新手来说,是非常重要的,可大大减少在学习过程中遇到的各种各样的坑,说到最后,也算是助人为乐吧!下面我们从零开始进行SSM框架的搭建,在介绍最后,我会把项目部署在GitHub以便需要Demo的亲朋好友们进行下载~~~
开源git地址:https://github.com/yonghu86/SSM-Demo
本Demo是在IDEA下搭建的Maven项目,在进行下面阅读前先了解这一点!
【开发环境】
1.操作系统:Windows7 ×64 Sp1
![](https://img.haomeiwen.com/i1459766/fbe206051c527ff7.png)
2.Java-Version:1.8.0_101
![](https://img.haomeiwen.com/i1459766/be6dbb60223d4261.png)
3.IDE:IntelliJ IDEA 2017.2.2 x64
![](https://img.haomeiwen.com/i1459766/37a000d6defbed98.png)
一、新建项目
运行IDEA,进入初始化界面,然后我们选择新建项目(进入主界面新建项目也是一样的)
![](https://img.haomeiwen.com/i1459766/ec0d6f53244836c9.png)
在Maven选项卡里面找到对应的java web选项,然后我们点下一步
![](https://img.haomeiwen.com/i1459766/22804a864fdad538.png)
这一步填入组织等信息,这里比较随意,按照自己的需求进行填写,然后下一步
![](https://img.haomeiwen.com/i1459766/8651f00babbd445d.png)
这里我早已配置好本地Maven仓库,因此直接默认即可。如果没进行配置本地默认仓库的话,请网上查找对应的资料进行配置
![](https://img.haomeiwen.com/i1459766/39c888cc53e17042.png)
输入Project name,和需要保存的路径,然后finish
![](https://img.haomeiwen.com/i1459766/0b4a488c92a49c8c.png)
去泡一杯咖啡吧,这里需要一小段时间哦~
稍等片刻,idea已经为我们自动建好了一切。到这里,我们的第一步,新建项目阶段已经完成,欢庆一下,进入下一个阶段。
![](https://img.haomeiwen.com/i1459766/b9054150187c23e3.png)
新建好项目后,我们首先打开SSM_Demo,修改一下JDK版本。
![](https://img.haomeiwen.com/i1459766/183b60ba32e87dd2.png)
![](https://img.haomeiwen.com/i1459766/433073fd7888833b.png)
在settings里面对项目版本进行修改:
![](https://img.haomeiwen.com/i1459766/03fb350e23ca49e9.png)
原来是1_5,现在改为1_8,可能会存在spring等框架版本和jdk版本不兼容问题,因此,提前升级了版本。
二、目录结构调整
首先我们配置Maven的项目结构,选择Project Structure
![](https://img.haomeiwen.com/i1459766/a85af6e434fdb524.png)
选择Modules标签页,然后新建并标识对应的项目结构
![](https://img.haomeiwen.com/i1459766/ee56924781a97994.png)
最终的文件结构如下所示:
![](https://img.haomeiwen.com/i1459766/d95a6791bf49e6d7.png)
![](https://img.haomeiwen.com/i1459766/a909f36fef0ba4a5.png)
- Java为主Java代码文件夹
- Controllers 控制器文件文件夹
- Dao (数据访问)层文件夹
- Service(业务逻辑)层文件夹
- Entity(实体)层文件夹
- resources资源文件夹
- mapper mybatis sql文件夹
- webapp web页面文件夹
- Test 测试文件夹
三、Maven包的初始化
Maven是采用配置文件的方式进行jar包的自动导入,因此,我们需要进行对配置文件的修改来进行jar包的导入。
打开pom.xml文件
![](https://img.haomeiwen.com/i1459766/61ba4b9a601fa074.png)
添加我们将会用到的一系列jar包配置(这里将我的配置直接复制过来,作为参考)
<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>QX_JFrame</groupId>
<artifactId>Demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--Unit Test - 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!--Spring transaction-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.5.RELEASE</version>
</dependency>
<!--Spring Web + Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.3</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
<!--mysql jdbc-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--c3p0-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!--NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--file upload jar package-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--json-->
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<!--json serialize and deserialization-->
<!-- 引入fastjson依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
<!-- 引入gson依赖 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<!--Base64 加解密-->
<!-- https://mvnrepository.com/artifact/net.iharder/base64 -->
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>2.3.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!--log4j-->
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations-java5</artifactId>
<version>RELEASE</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<finalName>Demo</finalName>
</build>
</project>
待配置好的jar包都自动下载并导入后,我们maven包的导入阶段就完成了,下面我们开始整合各个组件。
四、Spring MVC的配置
在resources资源文件夹下新建spring-servlet.xml文件,并在配置文件中声明spring mvc框架对控制器、页面、资源的访问
![](https://img.haomeiwen.com/i1459766/e02695ca1d65cea7.png)
在其中添加下面配置标签信息:
<?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: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-3.1.xsd">
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
<mvc:annotation-driven >
</mvc:annotation-driven>
<!-- 启动包扫描功能,以便注册带有@Controllers、@service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="Controllers" />
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/> <!-- 前缀 -->
<property name="suffix" value=".jsp"/> <!-- 后缀 -->
</bean>
<!-- 访问静态文件(jpg,js,css)的方法 -->
<!--<mvc:resources location="/files/" mapping="/files/**" />-->
<!--<mvc:resources location="/scripts/" mapping="/scripts/**" />-->
<!--<mvc:resources location="/styles/" mapping="/styles/**" />-->
<!--<mvc:resources location="/Views/" mapping="/Views/**" />-->
</beans>
![](https://img.haomeiwen.com/i1459766/27e1bd4ed8508284.png)
这里的Controllers对应的是我们之前新建好的Controllers包文件夹。
对web.xml进行配置,将我们刚才添加的spring-servlet.xml配置进去
![](https://img.haomeiwen.com/i1459766/3725c2eb3b7a473b.png)
![](https://img.haomeiwen.com/i1459766/9557b01038190bb6.png)
这里的classpath为resources资源目录
这一步配置的web.xml内容如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring MVC配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--Spring-servlet.xml config-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<!-- load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法) -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
我们新建一个控制器测试一下(在Controllers包新建java类,RequestTestController):
![](https://img.haomeiwen.com/i1459766/855fb673e05d3218.png)
接下来在RequestTestController里面写一个rest api接口:
![](https://img.haomeiwen.com/i1459766/c7838bba147e3403.png)
接口代码如下:
package Controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/RequestTest")
public class RequestTestController {
@GetMapping()
public String TestString(){
return "this is a test string. Time:2017-10-29 20:42:00";
}
}
这样,我们便可以通过url地址来进行访问我们的接口数据
![](https://img.haomeiwen.com/i1459766/2f78c11699fc7fcf.png)
在右上角的运行服务器配置按钮,打开服务器配置项
![](https://img.haomeiwen.com/i1459766/285e28e1e008318f.png)
这里如果左侧列表是空的话,我们就需要点击加号进行服务器的添加,选择Tomcat Server下的Local。然后点击刚刚添加的标签,在右侧输入Server Name,下面会自动提示设置编译方式,选一个编译方式,然后点击OK即可(这一步的前提是装好了Tomcat服务器,如果没有安装,则需要先安装Tomcat服务器)。
然后我们点击右上角的运行,如果没有什么问题的话,我们的控制台界面会提示服务启动成功!(我这样下来是不会出问题的)
![](https://img.haomeiwen.com/i1459766/f9799bdc68382350.png)
等浏览器打开以后,我们输入我们配置的api地址:http://localhost:8080/api/RequestTest
![](https://img.haomeiwen.com/i1459766/8e53f985f9716fdb.png)
这样,spring mvc已经成功整合到了项目里面!
五、Spring和Mybatis的配置
稍歇片刻后,我们继续进行Mybatis和Spring组件的整合...
先添加jdbc.properties(JDBC连接配置文件,当然这个文件里面的内容直接写到mybatis配置文件里面也是可以的)
![](https://img.haomeiwen.com/i1459766/4dcddd39de109e3f.png)
内容如下:
#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://***.***.***\:3306/db_test?useSSL=false
jdbc.username=username
jdbc.password=password
#c3p0连接池信息
c3p0.minPoolSize=10
c3p0.maxPoolSize=100
#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数
c3p0.acquireIncrement=3
#定义在从数据库获取新连接失败后重复尝试的次数
c3p0.acquireRetryAttempts=60
#两次连接中间隔时间,单位毫秒
c3p0.acquireRetryDelay=1000
#连接关闭时默认将所有未提交的操作回滚
c3p0.autoCommitOnClose=false
#当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限
c3p0.checkoutTimeout=3000
#每120秒检查所有连接池中的空闲连接。Default: 0
c3p0.idleConnectionTestPeriod=120
#最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
c3p0.maxIdleTime=600
#如果设为true那么在取得连接的同时将校验连接的有效性。Default: false
c3p0.testConnectionOnCheckin=false
#如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
c3p0.maxStatements=8
#maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
c3p0.maxStatementsPerConnection=5
#自动超时回收Connection
c3p0.unreturnedConnectionTimeout=25
jdbc.properties
继续在resources文件夹里面添加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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
<property name="maxStatements" value="${c3p0.maxStatements}"/>
<property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/>
<property name="unreturnedConnectionTimeout" value="${c3p0.unreturnedConnectionTimeout}"/>
</bean>
<!-- 配置mybatisSqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置mybatis mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="Dao"/>
<!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
spring-mybatis.xml
添加spring支持(applicationContext.xml),并在spring支持里面将mybatis配置文件进行引入
内容如下:
<?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:context="http://www.springframework.org/schema/context"
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.xsd">
<context:annotation-config />
<!-- 配置component所在的包,自动加载需要管理的Bean -->
<context:component-scan base-package="Service,Dao" />
<import resource="spring-mybatis.xml" />
</beans>
applicationContext.xml配置文件是对spring的配置,我们配置spring组件的扫描包围Service和Dao层目录,然后将spring-mybatis.xml配置文件导入.
完成这三个后的文件目录是这样子的:
![](https://img.haomeiwen.com/i1459766/92866e4a59d0a131.png)
target文件夹是刚才编译运行时候自动产生的,不要惊慌~~~
完成这几步后,我们还需要将spring的配置加载到已有的框架中去,打开web.xml文件,进行添加spring配置
在刚才的web-app标签内继续添加spring支持:
![](https://img.haomeiwen.com/i1459766/450355f84b9bc6d4.png)
此刻完整的web.xml文件内容如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- Spring MVC配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--Spring-servlet.xml config-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<!-- load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法) -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--spring listener config-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置log4j配置文件的路径,可以是xml或 properties(此参数必须配)-->
<!--<context-param>-->
<!--<param-name>log4jConfigLocation</param-name>-->
<!--<param-value>classpath:log4j.properties</param-value>-->
<!--</context-param>-->
</web-app>
web.xml
到此刻,我们的spring、mybatis已经整合完毕,接下来稍歇片刻,我们进行demo的完成。
六、demo的构建
打开数据库,我们新建一个数据库,并设计两张测试表,student和studentclass
![](https://img.haomeiwen.com/i1459766/18a3bbc526dfe7e8.png)
student表的设计如下:
![](https://img.haomeiwen.com/i1459766/ec74031ede802a82.png)
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`Uid` binary(36) NOT NULL COMMENT 'Uid',
`Name` varchar(20) NOT NULL,
`Age` int(3) NOT NULL,
`ClassId` int(3) NOT NULL,
PRIMARY KEY (`Uid`),
KEY `StudentClass` (`ClassId`),
CONSTRAINT `StudentClass` FOREIGN KEY (`ClassId`) REFERENCES `studentclass` (`ClassId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
studentclass表的设计如下:
![](https://img.haomeiwen.com/i1459766/1c8856483d9cc69f.png)
-- ----------------------------
-- Table structure for `studentclass`
-- ----------------------------
DROP TABLE IF EXISTS `studentclass`;
CREATE TABLE `studentclass` (
`ClassId` int(3) NOT NULL AUTO_INCREMENT,
`ClassName` varchar(10) DEFAULT NULL,
PRIMARY KEY (`ClassId`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
将数据库建好后,我们进行Entity,Dao,Service层以及mapper文件的的编写。
首先在mapper文件夹新建一个mapper文件:StudentMapper.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="Dao.StudentMapper">
<resultMap id="BaseResultMap" type="Entity.Student">
<id column="Uid" jdbcType="BINARY" property="uid" />
<result column="Name" jdbcType="VARCHAR" property="name" />
<result column="Age" jdbcType="INTEGER" property="age" />
<result column="ClassId" jdbcType="INTEGER" property="classid" />
</resultMap>
<sql id="Base_Column_List">
Uid, Name, Age, ClassId
</sql>
<select id="selectByPrimaryKey" parameterType="byte[]" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
where Uid = #{uid,jdbcType=BINARY}
</select>
<select id="selectByCondition" parameterType="Entity.Student" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
from student
<where>
1=1
<if test="uid != null">
and Uid=#{uid,jdbcType=BINARY}
</if>
<if test="name != null">
and Name=#{name,jdbcType=VARCHAR}
</if>
<if test="age != null">
and Age=#{age,jdbcType=INTEGER}
</if>
<if test="classid != null">
and ClassId=#{classid,jdbcType=INTEGER}
</if>
</where>
</select>
<delete id="deleteByPrimaryKey" parameterType="byte[]">
delete from student
where Uid = #{uid,jdbcType=BINARY}
</delete>
<insert id="insert" parameterType="Entity.Student">
insert into student (Uid, Name, Age,
ClassId)
values (#{uid,jdbcType=BINARY}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{classid,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="Entity.Student">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="uid != null">
Uid,
</if>
<if test="name != null">
Name,
</if>
<if test="age != null">
Age,
</if>
<if test="classid != null">
ClassId,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="uid != null">
#{uid,jdbcType=BINARY},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="classid != null">
#{classid,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="Entity.Student">
update student
<set>
<if test="name != null">
Name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
Age = #{age,jdbcType=INTEGER},
</if>
<if test="classid != null">
ClassId = #{classid,jdbcType=INTEGER},
</if>
</set>
where Uid = #{uid,jdbcType=BINARY}
</update>
<update id="updateByPrimaryKey" parameterType="Entity.Student">
update student
set Name = #{name,jdbcType=VARCHAR},
Age = #{age,jdbcType=INTEGER},
ClassId = #{classid,jdbcType=INTEGER}
where Uid = #{uid,jdbcType=BINARY}
</update>
</mapper>
以上这段代码是直接使用mybatis generator直接进行生成的,如果不想手写的话(手写容易出错),可以直接使用该工具进行生成
添加Entity实体
![](https://img.haomeiwen.com/i1459766/92cb76bcdcf486d2.png)
package Entity;
public class Student {
private byte[] uid;
private String name;
private Integer age;
private Integer classid;
public byte[] getUid() {
return uid;
}
public void setUid(byte[] uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getClassid() {
return classid;
}
public void setClassid(Integer classid) {
this.classid = classid;
}
}
在Dao层写Mybatis接口(不需要写实现类,mybatis不需要),新建StudentMapper
![](https://img.haomeiwen.com/i1459766/6d2b74710be4ec2c.png)
package Dao;
import Entity.Student;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentMapper {
int deleteByPrimaryKey(byte[] uid);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(byte[] uid);
List<Student> selectByCondition(Student record);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
在Service层写对Dao层的访问逻辑,当然Demo没有什么业务处理逻辑,仅作为Demo
![](https://img.haomeiwen.com/i1459766/313bc889ab7e5ae3.png)
IStudentService 接口:
package Service;
import Entity.Student;
import java.util.List;
public interface IStudentService {
int deleteByPrimaryKey(byte[] uid);
int insert(Student record);
int insertSelective(Student record);
Student selectByPrimaryKey(byte[] uid);
List<Student> selectByCondition(Student record);
int updateByPrimaryKeySelective(Student record);
int updateByPrimaryKey(Student record);
}
StudentService 实现了 IStudentService 接口:
package Service;
import Dao.StudentMapper;
import Entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService implements IStudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public int deleteByPrimaryKey(byte[] uid) {
return studentMapper.deleteByPrimaryKey(uid);
}
@Override
public int insert(Student record) {
return studentMapper.insert(record);
}
@Override
public int insertSelective(Student record) {
return studentMapper.insertSelective(record);
}
@Override
public Student selectByPrimaryKey(byte[] uid) {
return studentMapper.selectByPrimaryKey(uid);
}
@Override
public List<Student> selectByCondition(Student record) {
return studentMapper.selectByCondition(record);
}
@Override
public int updateByPrimaryKeySelective(Student record) {
return studentMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Student record) {
return studentMapper.updateByPrimaryKey(record);
}
}
然后我们写一个StudentController用于调用Service
![](https://img.haomeiwen.com/i1459766/f19cefce77dba945.png)
package Controllers;
import Entity.Student;
import Service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/Student")
public class StudentController {
@Autowired
private IStudentService service;
@GetMapping()
public String Get() {
List<Student> students = service.selectByCondition(new Student());
String jsonResult = com.alibaba.fastjson.JSON.toJSONString(students);
return jsonResult;
}
}
走到这一步的代码目录结构是这样子的:
![](https://img.haomeiwen.com/i1459766/8914b448d77fd285.png)
如果进行顺利的话,我们运行我们的Tomacat服务器,并调用我们的新接口:http://localhost:8080/api/Student
运行时候,别忘记了修改jdbc.properties文件里的连接url以及用户名密码!!!
![](https://img.haomeiwen.com/i1459766/393016e3eb52b07e.png)
![](https://img.haomeiwen.com/i1459766/f2d398e28d66a107.png)
哇,数据成功显示!(别把这个数据当成你会真的显示出来的一样,这是我数据库原有的数据,哈哈哈)
![](https://img.haomeiwen.com/i1459766/1271ae2e54430a9b.png)
还不快去添加几条数据调用一下试试嘛~
七、结尾
至此,我们的SSM框架已经基本搭建完毕,我们已经用我们搭建的Demo从真实的数据库中获取到了数据,并转成了Json格式,在浏览器中用Rest api接口的形式获取到了。
该项目源代码可以在Github上找到,如果需要的可以直接去下载->
https://github.com/yonghu86/SSM-Demo (不赶紧访问点个Star嘛?)****
网友评论