SSM(Spring+SpringMVC+Mybatis)框架搭建详细教程【附源代码Demo】
【前言】
应某网络友人邀约,需要一个SSM框架的Demo作为基础学习资料,于是乎,就有了本文。一个从零开始的SSM框架Demo对一个新手来说,是非常重要的,可大大减少在学习过程中遇到的各种各样的坑,说到最后,也算是助人为乐吧!下面我们从零开始进行SSM框架的搭建,在介绍最后,我会把项目部署在GitHub以便需要Demo的亲朋好友们进行下载~~~
https://github.com/dong666/SSM-Demo (访问记得Star哦~)
本Demo是在IDEA下搭建的Maven项目,在进行下面阅读前先了解这一点!
【开发环境】
1.操作系统:Windows7 ×64 Sp1

2.Java-Version:1.8.0_101

3.IDE:IntelliJ IDEA 2017.2.2 x64

一、新建项目
运行IDEA,进入初始化界面,然后我们选择新建项目(进入主界面新建项目也是一样的)

在Maven选项卡里面找到对应的java web选项,然后我们点下一步

这一步填入组织等信息,这里比较随意,按照自己的需求进行填写,然后下一步

这里我早已配置好本地Maven仓库,因此直接默认即可。如果没进行配置本地默认仓库的话,请网上查找对应的资料进行配置

输入Project name,和需要保存的路径,然后finish

去泡一杯咖啡吧,这里需要一小段时间哦~
稍等片刻,idea已经为我们自动建好了一切。到这里,我们的第一步,新建项目阶段已经完成,欢庆一下,进入下一个阶段。

新建好项目后,我们首先打开SSM_Demo,修改一下JDK版本。


在settings里面对项目版本进行修改:

原来是1_5,现在改为1_8,可能会存在spring等框架版本和jdk版本不兼容问题,因此,提前升级了版本。
二、目录结构调整
首先我们配置Maven的项目结构,选择Project Structure

选择Modules标签页,然后新建并标识对应的项目结构

最终的文件结构如下所示:


- Java为主Java代码文件夹
- Controllers 控制器文件文件夹
- Dao (数据访问)层文件夹
- Service(业务逻辑)层文件夹
- Entity(实体)层文件夹
- resources资源文件夹
- mapper mybatis sql文件夹
- webapp web页面文件夹
- Test 测试文件夹
三、Maven包的初始化
Maven是采用配置文件的方式进行jar包的自动导入,因此,我们需要进行对配置文件的修改来进行jar包的导入。
打开pom.xml文件

添加我们将会用到的一系列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框架对控制器、页面、资源的访问

在其中添加下面配置标签信息:
<?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>

这里的Controllers对应的是我们之前新建好的Controllers包文件夹。
对web.xml进行配置,将我们刚才添加的spring-servlet.xml配置进去


这里的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):

接下来在RequestTestController里面写一个rest api接口:

接口代码如下:
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地址来进行访问我们的接口数据

在右上角的运行服务器配置按钮,打开服务器配置项

这里如果左侧列表是空的话,我们就需要点击加号进行服务器的添加,选择Tomcat Server下的Local。然后点击刚刚添加的标签,在右侧输入Server Name,下面会自动提示设置编译方式,选一个编译方式,然后点击OK即可(这一步的前提是装好了Tomcat服务器,如果没有安装,则需要先安装Tomcat服务器)。
然后我们点击右上角的运行,如果没有什么问题的话,我们的控制台界面会提示服务启动成功!(我这样下来是不会出问题的)

等浏览器打开以后,我们输入我们配置的api地址:http://localhost:8080/api/RequestTest

这样,spring mvc已经成功整合到了项目里面!
五、Spring和Mybatis的配置
稍歇片刻后,我们继续进行Mybatis和Spring组件的整合...
先添加jdbc.properties(JDBC连接配置文件,当然这个文件里面的内容直接写到mybatis配置文件里面也是可以的)

内容如下:
#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配置文件导入.
完成这三个后的文件目录是这样子的:

target文件夹是刚才编译运行时候自动产生的,不要惊慌~~~
完成这几步后,我们还需要将spring的配置加载到已有的框架中去,打开web.xml文件,进行添加spring配置
在刚才的web-app标签内继续添加spring支持:

此刻完整的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

student表的设计如下:

-- ---------------------------- -- 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表的设计如下:

-- ---------------------------- -- 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直接进行生成的,如果不想手写的话(手写容易出错),可以直接使用该工具进行生成,该工具的下载以及使用参见本人博客地址:http://www.cnblogs.com/qixiaoyizhan/p/7597315.html
添加Entity实体

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

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

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

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;
}
}
走到这一步的代码目录结构是这样子的:

如果进行顺利的话,我们运行我们的Tomacat服务器,并调用我们的新接口:http://localhost:8080/api/Student
运行时候,别忘记了修改jdbc.properties文件里的连接url以及用户名密码!!!


哇,数据成功显示!(别把这个数据当成你会真的显示出来的一样,这是我数据库原有的数据,哈哈哈)

还不快去添加几条数据调用一下试试嘛~
七、结尾
至此,我们的SSM框架已经基本搭建完毕,我们已经用我们搭建的Demo从真实的数据库中获取到了数据,并转成了Json格式,在浏览器中用Rest api接口的形式获取到了。
该项目源代码可以在Github上找到,如果需要的可以直接去下载->
https://github.com/dong666/SSM-Demo (不赶紧访问点个Star嘛?)
如果在搭建中还有任何疑问,随时可以在下面的签名联系方式中找到我~ 茫茫人海中,也是有缘~~~
如果有推荐工作的也可以在下面的联系方式中找到我哦,如果是这样的话,我是真的感激呢!!!~~~
SSM(Spring+SpringMVC+Mybatis)框架搭建详细教程【附源代码Demo】的更多相关文章
- SSM(Spring +SpringMVC + Mybatis)框架搭建
SSM(Spring +SpringMVC + Mybatis)框架的搭建 最近通过学习别人博客发表的SSM搭建Demo,尝试去搭建一个简单的SSMDemo---实现的功能是对用户增删改查的操作 参考 ...
- 基于Maven的ssm(spring+springMvc+Mybatis)框架搭建
前言 本demo是在idea下搭建的maven项目,数据库使用Mysql,jdk版本是1.8.0_171,ideal:2017.3.5 一.新建项目 1.file->new->porjec ...
- SSM(Spring+SpringMVC+Mybatis)框架环境搭建(整合步骤)(一)
1. 前言 最近在写毕设过程中,重新梳理了一遍SSM框架,特此记录一下. 附上源码:https://gitee.com/niceyoo/jeenotes-ssm 2. 概述 在写代码之前我们先了解一下 ...
- SSM(Spring,SpringMVC,Mybatis)框架整合项目
快速上手SSM(Spring,SpringMVC,Mybatis)框架整合项目 环境要求: IDEA MySQL 8.0.25 Tomcat 9 Maven 3.6 数据库环境: 创建一个存放书籍数据 ...
- SSM(Spring + Springmvc + Mybatis)框架面试题
JAVA SSM框架基础面试题https://blog.csdn.net/qq_39031310/article/details/83050192 SSM(Spring + Springmvc + M ...
- SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释(转)
原文:https://blog.csdn.net/yijiemamin/article/details/51156189# 这几天一直在整合SSM框架,虽然网上有很多已经整合好的,但是对于里面的配置文 ...
- 0927-转载:SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释
这篇文章暂时只对框架中所要用到的配置文件进行解释说明,而且是针对注解形式的,框架运转的具体流程过两天再进行总结. spring+springmvc+mybatis框架中用到了三个XML配置文件:web ...
- SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释
这几天一直在整合SSM框架,虽然网上有很多已经整合好的,但是对于里面的配置文件并没有进行过多的说明,很多人知其然不知其所以然,经过几天的搜索和整理,今天总算对其中的XML配置文件有了一定的了解,所以拿 ...
- SSM(Spring+SpringMVC+MyBatis)框架整合开发流程
回忆了 Spring.SpringMVC.MyBatis 框架整合,完善一个小demo,包括基本的增删改查功能. 开发环境 IDEA MySQL 5.7 Tomcat 9 Maven 3.2.5 需要 ...
- [置顶]
Java Web学习总结(24)——SSM(Spring+SpringMVC+MyBatis)框架快速整合入门教程
1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One ...
随机推荐
- lintcode.68 二叉树后序遍历
二叉树的后序遍历 描述 笔记 数据 评测 给出一棵二叉树,返回其节点值的后序遍历. 您在真实的面试中是否遇到过这个题? Yes 样例 给出一棵二叉树 {1,#,2,3}, 1 \ 2 / 3 返 ...
- 如何快速生成企业Web应用
随着互联网的发展,企业认识到"电子化"和"无纸化"办公是一种必然趋势,但是企业在信息化建设中经常望而却步,主要原因是高昂的建设成本与不可以预估的结果风险.另外软 ...
- JPA常用注解(转载)
转自:http://blog.csdn.net/wanghuan203/article/details/8698102 JPA全称Java Persistence API.JPA通过JDK 5.0注解 ...
- python generator(生成器)
a=(x*2 for x in range(1000)) # print(a.next())#python2使用 print(a.__next__()) #python3使用 print(next(a ...
- 工作中对数组的一些处理,整理(结合underscore.js)
1.数组里边相同元素提取成map,并以'',''分隔 例如:var arr = [{a:"xx",b:''xxx''},{a:"xxx",b:''xxxxx'' ...
- java 多态(动态绑定)
一.面向对象最核心的机制--动态绑定,也叫多态 1.1.通过下面的例子理解动态绑定,即多态 1 package javastudy.summary; 2 3 class Animal { 4 /** ...
- [C#]关于DBNULL的解释
1 概述 如下例子,你觉得有什么问题?如你能很快的找出问题,并且解决它,那么你可以跳过本篇文章,谢谢~~. List<Base_Employee> ltPI = new List< ...
- iOS根据域名获取ip地址
引入头文件 #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> //根据域名获取ip ...
- oracle数据库知识点
1.oracle启动后的服务 1. Oracle ORCL VSS Writer Service:Oracle卷映射拷贝写入服务,VSS(Volume Shadow Copy Service)能够让存 ...
- NOIP2017SummerTraining0705
个人感受:这一场考试是网开着的,然后第一题就水过了,第二三题应该是暴力吧,然后各水了50.拿了200分.排名第10. 问题 A: 重复字符串 时间限制: 1 Sec 内存限制: 256 MB提交: ...