http://www.cnblogs.com/qixiaoyizhan/p/7751732.html

【前言】

  应某网络友人邀约,需要一个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包配置(这里将我的配置直接复制过来,作为参考)

复制代码
  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4   <groupId>QX_JFrame</groupId>
  5   <artifactId>Demo</artifactId>
  6   <packaging>war</packaging>
  7   <version>1.0-SNAPSHOT</version>
  8   <name>Demo Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   <dependencies>
 11     <!--Unit Test - 单元测试-->
 12     <dependency>
 13       <groupId>junit</groupId>
 14       <artifactId>junit</artifactId>
 15       <version>4.12</version>
 17     </dependency>
 18     <!--Spring-->
 19     <dependency>
 20       <groupId>org.springframework</groupId>
 21       <artifactId>spring-core</artifactId>
 22       <version>4.3.5.RELEASE</version>
 23     </dependency>
 24     <dependency>
 25       <groupId>org.springframework</groupId>
 26       <artifactId>spring-aop</artifactId>
 27       <version>4.3.5.RELEASE</version>
 28     </dependency>
 29     <dependency>
 30       <groupId>org.springframework</groupId>
 31       <artifactId>spring-orm</artifactId>
 32       <version>4.3.5.RELEASE</version>
 33     </dependency>
 34     <!--Spring transaction-->
 35     <dependency>
 36       <groupId>org.springframework</groupId>
 37       <artifactId>spring-tx</artifactId>
 38       <version>4.3.5.RELEASE</version>
 39     </dependency>
 40     <dependency>
 41       <groupId>org.springframework</groupId>
 42       <artifactId>spring-test</artifactId>
 43       <version>4.3.5.RELEASE</version>
 44     </dependency>
 45     <dependency>
 46       <groupId>org.springframework</groupId>
 47       <artifactId>spring-mock</artifactId>
 48       <version>2.0.8</version>
 49     </dependency>
 50     <dependency>
 51       <groupId>org.springframework</groupId>
 52       <artifactId>spring-jdbc</artifactId>
 53       <version>4.3.5.RELEASE</version>
 54     </dependency>
 55     <dependency>
 56       <groupId>org.springframework</groupId>
 57       <artifactId>spring-context</artifactId>
 58       <version>4.3.5.RELEASE</version>
 59     </dependency>
 60     <dependency>
 61       <groupId>org.springframework</groupId>
 62       <artifactId>spring-context-support</artifactId>
 63       <version>4.3.5.RELEASE</version>
 64     </dependency>
 65     <dependency>
 66       <groupId>org.springframework</groupId>
 67       <artifactId>spring-expression</artifactId>
 68       <version>4.3.5.RELEASE</version>
 69     </dependency>
 70     <!--Spring Web + Spring MVC-->
 71     <dependency>
 72       <groupId>org.springframework</groupId>
 73       <artifactId>spring-web</artifactId>
 74       <version>4.3.1.RELEASE</version>
 75     </dependency>
 76     <dependency>
 77       <groupId>org.springframework</groupId>
 78       <artifactId>spring-webmvc</artifactId>
 79       <version>4.3.1.RELEASE</version>
 80     </dependency>
 81 
 82     <dependency>
 83       <groupId>com.github.pagehelper</groupId>
 84       <artifactId>pagehelper</artifactId>
 85       <version>3.7.3</version>
 86     </dependency>
 87     <dependency>
 88       <groupId>com.github.jsqlparser</groupId>
 89       <artifactId>jsqlparser</artifactId>
 90       <version>0.9.1</version>
 91     </dependency>
 92     <!--mysql jdbc-->
 93     <dependency>
 94       <groupId>mysql</groupId>
 95       <artifactId>mysql-connector-java</artifactId>
 96       <version>5.1.38</version>
 97     </dependency>
 98     <!--c3p0-->
 99     <dependency>
100       <groupId>c3p0</groupId>
101       <artifactId>c3p0</artifactId>
102       <version>0.9.1.2</version>
103     </dependency>
104     <!--NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config-->
105     <!-- https://mvnrepository.com/artifact/jstl/jstl -->
106     <dependency>
107       <groupId>jstl</groupId>
108       <artifactId>jstl</artifactId>
109       <version>1.2</version>
110     </dependency>
111     <!--file upload jar package-->
112     <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
113     <dependency>
114       <groupId>commons-fileupload</groupId>
115       <artifactId>commons-fileupload</artifactId>
116       <version>1.3.1</version>
117     </dependency>
118     <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
119     <dependency>
120       <groupId>commons-io</groupId>
121       <artifactId>commons-io</artifactId>
122       <version>2.4</version>
123     </dependency>
124     <!--json-->
125     <!-- https://mvnrepository.com/artifact/org.json/json -->
126     <dependency>
127       <groupId>org.json</groupId>
128       <artifactId>json</artifactId>
129       <version>20160212</version>
130     </dependency>
131     <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
132     <dependency>
133       <groupId>net.sf.json-lib</groupId>
134       <artifactId>json-lib</artifactId>
135       <version>2.4</version>
136     </dependency>
137     <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
138     <dependency>
139       <groupId>commons-lang</groupId>
140       <artifactId>commons-lang</artifactId>
141       <version>2.6</version>
142     </dependency>
143     <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
144     <dependency>
145       <groupId>commons-beanutils</groupId>
146       <artifactId>commons-beanutils</artifactId>
147       <version>1.8.3</version>
148     </dependency>
149     <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
150     <dependency>
151       <groupId>commons-collections</groupId>
152       <artifactId>commons-collections</artifactId>
153       <version>3.2.1</version>
154     </dependency>
155     <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
156     <dependency>
157       <groupId>commons-logging</groupId>
158       <artifactId>commons-logging</artifactId>
159       <version>1.2</version>
160     </dependency>
161     <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
162     <dependency>
163       <groupId>net.sf.ezmorph</groupId>
164       <artifactId>ezmorph</artifactId>
165       <version>1.0.6</version>
166     </dependency>
167     <!--json serialize and deserialization-->
168     <!-- 引入fastjson依赖 -->
169     <dependency>
170       <groupId>com.alibaba</groupId>
171       <artifactId>fastjson</artifactId>
172       <version>1.2.12</version>
173     </dependency>
174     <!-- 引入gson依赖 -->
175     <dependency>
176       <groupId>com.google.code.gson</groupId>
177       <artifactId>gson</artifactId>
178       <version>2.6.2</version>
179     </dependency>
180     <!--Base64 加解密-->
181     <!-- https://mvnrepository.com/artifact/net.iharder/base64 -->
182     <dependency>
183       <groupId>net.iharder</groupId>
184       <artifactId>base64</artifactId>
185       <version>2.3.8</version>
186     </dependency>
187     <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
188     <dependency>
189       <groupId>commons-codec</groupId>
190       <artifactId>commons-codec</artifactId>
191       <version>1.10</version>
192     </dependency>
193     <!--log4j-->
194     <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
195     <dependency>
196       <groupId>org.apache.logging.log4j</groupId>
197       <artifactId>log4j-core</artifactId>
198       <version>2.6.2</version>
199     </dependency>
200     <dependency>
201       <groupId>org.jetbrains</groupId>
202       <artifactId>annotations-java5</artifactId>
203       <version>RELEASE</version>
204     </dependency>
205     <!--mybatis-->
206     <dependency>
207       <groupId>org.mybatis</groupId>
208       <artifactId>mybatis</artifactId>
209       <version>3.3.0</version>
210     </dependency>
211     <dependency>
212       <groupId>org.mybatis</groupId>
213       <artifactId>mybatis-spring</artifactId>
214       <version>1.2.3</version>
215     </dependency>
216   </dependencies>
217   <build>
218     <finalName>Demo</finalName>
219   </build>
220 </project>
复制代码

  待配置好的jar包都自动下载并导入后,我们maven包的导入阶段就完成了,下面我们开始整合各个组件。

四、Spring MVC的配置

   在resources资源文件夹下新建spring-servlet.xml文件,并在配置文件中声明spring mvc框架对控制器、页面、资源的访问

  

  在其中添加下面配置标签信息:

复制代码
 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/beans
 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 8 http://www.springframework.org/schema/context
 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
12 
13     <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
14     <mvc:annotation-driven >
15 
16     </mvc:annotation-driven>
17 
18     <!-- 启动包扫描功能,以便注册带有@Controllers、@service、@repository、@Component等注解的类成为spring的bean -->
19     <context:component-scan base-package="Controllers" />
20     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
21     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
22         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
23         <property name="prefix" value="/"/>    <!-- 前缀 -->
24         <property name="suffix" value=".jsp"/>    <!-- 后缀 -->
25     </bean>
26     <!-- 访问静态文件(jpg,js,css)的方法 -->
27     <!--<mvc:resources location="/files/" mapping="/files/**" />-->
28     <!--<mvc:resources location="/scripts/" mapping="/scripts/**" />-->
29     <!--<mvc:resources location="/styles/" mapping="/styles/**" />-->
30     <!--<mvc:resources location="/Views/" mapping="/Views/**" />-->
31 </beans>
复制代码

  

  这里的Controllers对应的是我们之前新建好的Controllers包文件夹。

  对web.xml进行配置,将我们刚才添加的spring-servlet.xml配置进去

  

  

  这里的classpath为resources资源目录

  这一步配置的web.xml内容如下:

复制代码
 1 <!DOCTYPE web-app PUBLIC
 2         "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3         "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5          xmlns="http://java.sun.com/xml/ns/javaee"
 6          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 7          version="3.0">
 8   <display-name>Archetype Created Web Application</display-name>
 9   <welcome-file-list>
10     <welcome-file>/index.jsp</welcome-file>
11   </welcome-file-list>
12   <!-- Spring MVC配置 -->
13   <servlet>
14     <servlet-name>spring</servlet-name>
15     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16     <!--Spring-servlet.xml config-->
17     <init-param>
18       <param-name>contextConfigLocation</param-name>
19       <param-value>classpath:spring-servlet.xml</param-value>
20     </init-param>
21     <!-- load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法) -->
22     <load-on-startup>1</load-on-startup>
23   </servlet>
24   <servlet-mapping>
25     <servlet-name>spring</servlet-name>
26     <url-pattern>/</url-pattern>
27   </servlet-mapping>
28 </web-app>
复制代码

  我们新建一个控制器测试一下(在Controllers包新建java类,RequestTestController):

  

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

  

  接口代码如下:

复制代码
 1 package Controllers;
 2 
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 @RestController
 8 @RequestMapping("/api/RequestTest")
 9 public class RequestTestController {
10 
11     @GetMapping()
12     public String TestString(){
13         return "this is a test string. Time:2017-10-29 20:42:00";
14     }
15 }
复制代码

  这样,我们便可以通过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配置文件里面也是可以的)

  

  内容如下:

复制代码
 1 #mysql
 2 jdbc.driverClassName=com.mysql.jdbc.Driver
 3 jdbc.url=jdbc\:mysql\://***.***.***\:3306/db_test?useSSL=false
 4 jdbc.username=username
 5 jdbc.password=password
 6 
 7 #c3p0连接池信息
 8 c3p0.minPoolSize=10
 9 c3p0.maxPoolSize=100
10 #当连接池中的连接耗尽的时候c3p0一次同时获取的连接数
11 c3p0.acquireIncrement=3
12 #定义在从数据库获取新连接失败后重复尝试的次数
13 c3p0.acquireRetryAttempts=60
14 #两次连接中间隔时间,单位毫秒
15 c3p0.acquireRetryDelay=1000
16 #连接关闭时默认将所有未提交的操作回滚
17 c3p0.autoCommitOnClose=false
18 #当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限
19 c3p0.checkoutTimeout=3000
20 #每120秒检查所有连接池中的空闲连接。Default: 0
21 c3p0.idleConnectionTestPeriod=120
22 #最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0
23 c3p0.maxIdleTime=600
24 #如果设为true那么在取得连接的同时将校验连接的有效性。Default: false
25 c3p0.testConnectionOnCheckin=false
26 #如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0
27 c3p0.maxStatements=8
28 #maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0
29 c3p0.maxStatementsPerConnection=5
30 #自动超时回收Connection
31 c3p0.unreturnedConnectionTimeout=25
复制代码

  继续在resources文件夹里面添加mybatis配置文件 spring-mybatis.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        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">
 5 
 6     <bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 7         <property name="locations">
 8             <list>
 9                 <value>classpath:jdbc.properties</value>
10             </list>
11         </property>
12     </bean>
13 
14     <!-- 配置数据源 -->
15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <property name="driverClass" value="${jdbc.driverClassName}"/>
17         <property name="jdbcUrl" value="${jdbc.url}"/>
18         <property name="user" value="${jdbc.username}"/>
19         <property name="password" value="${jdbc.password}"/>
20         <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
21         <property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
22         <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
23         <property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
24         <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
25         <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
26         <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
27         <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
28         <property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
29         <property name="maxStatements" value="${c3p0.maxStatements}"/>
30         <property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"/>
31         <property name="unreturnedConnectionTimeout" value="${c3p0.unreturnedConnectionTimeout}"/>
32     </bean>
33 
34     <!-- 配置mybatisSqlSessionFactoryBean -->
35     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
36         <property name="dataSource" ref="dataSource"/>
37         <property name="mapperLocations" value="classpath:mapper/*.xml"/>
38     </bean>
39     <!-- 配置mybatis mapper接口 -->
40     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
41         <property name="basePackage" value="Dao"/>
42         <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
43     </bean>
44 
45     <!-- 配置事务管理器 -->
46     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
47         <property name="dataSource" ref="dataSource"/>
48     </bean>
49 
50 </beans>
复制代码

  添加spring支持(applicationContext.xml),并在spring支持里面将mybatis配置文件进行引入

  内容如下:

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3         xmlns="http://www.springframework.org/schema/beans"
 4         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5         xmlns:context="http://www.springframework.org/schema/context"
 6         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">
 7 
 8     <context:annotation-config />
 9     <!-- 配置component所在的包,自动加载需要管理的Bean -->
10     <context:component-scan base-package="Service,Dao" />
11     <import resource="spring-mybatis.xml" />
12 </beans>
复制代码

  applicationContext.xml配置文件是对spring的配置,我们配置spring组件的扫描包围Service和Dao层目录,然后将spring-mybatis.xml配置文件导入.

  完成这三个后的文件目录是这样子的:

  

  target文件夹是刚才编译运行时候自动产生的,不要惊慌~~~

  完成这几步后,我们还需要将spring的配置加载到已有的框架中去,打开web.xml文件,进行添加spring配置

  在刚才的web-app标签内继续添加spring支持:

  

  此刻完整的web.xml文件内容如下:

 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

复制代码
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3 <mapper namespace="Dao.StudentMapper">
  4     <resultMap id="BaseResultMap" type="Entity.Student">
  5         <id column="Uid" jdbcType="BINARY" property="uid" />
  6         <result column="Name" jdbcType="VARCHAR" property="name" />
  7         <result column="Age" jdbcType="INTEGER" property="age" />
  8         <result column="ClassId" jdbcType="INTEGER" property="classid" />
  9     </resultMap>
 10     <sql id="Base_Column_List">
 11         Uid, Name, Age, ClassId
 12     </sql>
 13     <select id="selectByPrimaryKey" parameterType="byte[]" resultMap="BaseResultMap">
 14         select
 15         <include refid="Base_Column_List" />
 16         from student
 17         where Uid = #{uid,jdbcType=BINARY}
 18     </select>
 19     <select id="selectByCondition" parameterType="Entity.Student" resultMap="BaseResultMap">
 20         SELECT
 21         <include refid="Base_Column_List"/>
 22         from student
 23         <where>
 24             1=1
 25             <if test="uid != null">
 26                 and Uid=#{uid,jdbcType=BINARY}
 27             </if>
 28             <if test="name != null">
 29                 and Name=#{name,jdbcType=VARCHAR}
 30             </if>
 31             <if test="age != null">
 32                 and Age=#{age,jdbcType=INTEGER}
 33             </if>
 34             <if test="classid != null">
 35                 and ClassId=#{classid,jdbcType=INTEGER}
 36             </if>
 37         </where>
 38     </select>
 39     <delete id="deleteByPrimaryKey" parameterType="byte[]">
 40         delete from student
 41         where Uid = #{uid,jdbcType=BINARY}
 42     </delete>
 43     <insert id="insert" parameterType="Entity.Student">
 44         insert into student (Uid, Name, Age,
 45         ClassId)
 46         values (#{uid,jdbcType=BINARY}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
 47         #{classid,jdbcType=INTEGER})
 48     </insert>
 49     <insert id="insertSelective" parameterType="Entity.Student">
 50         insert into student
 51         <trim prefix="(" suffix=")" suffixOverrides=",">
 52             <if test="uid != null">
 53                 Uid,
 54             </if>
 55             <if test="name != null">
 56                 Name,
 57             </if>
 58             <if test="age != null">
 59                 Age,
 60             </if>
 61             <if test="classid != null">
 62                 ClassId,
 63             </if>
 64         </trim>
 65         <trim prefix="values (" suffix=")" suffixOverrides=",">
 66             <if test="uid != null">
 67                 #{uid,jdbcType=BINARY},
 68             </if>
 69             <if test="name != null">
 70                 #{name,jdbcType=VARCHAR},
 71             </if>
 72             <if test="age != null">
 73                 #{age,jdbcType=INTEGER},
 74             </if>
 75             <if test="classid != null">
 76                 #{classid,jdbcType=INTEGER},
 77             </if>
 78         </trim>
 79     </insert>
 80     <update id="updateByPrimaryKeySelective" parameterType="Entity.Student">
 81         update student
 82         <set>
 83             <if test="name != null">
 84                 Name = #{name,jdbcType=VARCHAR},
 85             </if>
 86             <if test="age != null">
 87                 Age = #{age,jdbcType=INTEGER},
 88             </if>
 89             <if test="classid != null">
 90                 ClassId = #{classid,jdbcType=INTEGER},
 91             </if>
 92         </set>
 93         where Uid = #{uid,jdbcType=BINARY}
 94     </update>
 95     <update id="updateByPrimaryKey" parameterType="Entity.Student">
 96         update student
 97         set Name = #{name,jdbcType=VARCHAR},
 98         Age = #{age,jdbcType=INTEGER},
 99         ClassId = #{classid,jdbcType=INTEGER}
100         where Uid = #{uid,jdbcType=BINARY}
101     </update>
102 </mapper>
复制代码

  以上这段代码是直接使用mybatis generator直接进行生成的,如果不想手写的话(手写容易出错),可以直接使用该工具进行生成,该工具的下载以及使用参见本人博客地址:http://www.cnblogs.com/qixiaoyizhan/p/7597315.html

  添加Entity实体

  

复制代码
 1 package Entity;
 2 
 3 public class Student {
 4     private byte[] uid;
 5 
 6     private String name;
 7 
 8     private Integer age;
 9 
10     private Integer classid;
11 
12     public byte[] getUid() {
13         return uid;
14     }
15 
16     public void setUid(byte[] uid) {
17         this.uid = uid;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name == null ? null : name.trim();
26     }
27 
28     public Integer getAge() {
29         return age;
30     }
31 
32     public void setAge(Integer age) {
33         this.age = age;
34     }
35 
36     public Integer getClassid() {
37         return classid;
38     }
39 
40     public void setClassid(Integer classid) {
41         this.classid = classid;
42     }
43 }
复制代码

  在Dao层写Mybatis接口(不需要写实现类,mybatis不需要),新建StudentMapper

  

复制代码
 1 package Dao;
 2 
 3 import Entity.Student;
 4 import org.springframework.stereotype.Repository;
 5 
 6 import java.util.List;
 7 
 8 @Repository
 9 public interface StudentMapper {
10     int deleteByPrimaryKey(byte[] uid);
11 
12     int insert(Student record);
13 
14     int insertSelective(Student record);
15 
16     Student selectByPrimaryKey(byte[] uid);
17 
18     List<Student> selectByCondition(Student record);
19 
20     int updateByPrimaryKeySelective(Student record);
21 
22     int updateByPrimaryKey(Student record);
23 }
复制代码

  在Service层写对Dao层的访问逻辑,当然Demo没有什么业务处理逻辑,仅作为Demo

  

  IStudentService 接口:

复制代码
 1 package Service;
 2 
 3 import Entity.Student;
 4 
 5 import java.util.List;
 6 
 7 public interface IStudentService {
 8     int deleteByPrimaryKey(byte[] uid);
 9 
10     int insert(Student record);
11 
12     int insertSelective(Student record);
13 
14     Student selectByPrimaryKey(byte[] uid);
15 
16     List<Student> selectByCondition(Student record);
17 
18     int updateByPrimaryKeySelective(Student record);
19 
20     int updateByPrimaryKey(Student record);
21 }
复制代码

  StudentService 实现了 IStudentService 接口:

复制代码
 1 package Service;
 2 
 3 import Dao.StudentMapper;
 4 import Entity.Student;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import java.util.List;
 9 
10 @Service
11 public class StudentService implements IStudentService {
12     @Autowired
13     private StudentMapper studentMapper;
14 
15     @Override
16     public int deleteByPrimaryKey(byte[] uid) {
17         return studentMapper.deleteByPrimaryKey(uid);
18     }
19 
20     @Override
21     public int insert(Student record) {
22         return studentMapper.insert(record);
23     }
24 
25     @Override
26     public int insertSelective(Student record) {
27         return studentMapper.insertSelective(record);
28     }
29 
30     @Override
31     public Student selectByPrimaryKey(byte[] uid) {
32         return studentMapper.selectByPrimaryKey(uid);
33     }
34 
35     @Override
36     public List<Student> selectByCondition(Student record) {
37         return studentMapper.selectByCondition(record);
38     }
39 
40     @Override
41     public int updateByPrimaryKeySelective(Student record) {
42         return studentMapper.updateByPrimaryKeySelective(record);
43     }
44 
45     @Override
46     public int updateByPrimaryKey(Student record) {
47         return studentMapper.updateByPrimaryKey(record);
48     }
49 }
复制代码

  然后我们写一个StudentController用于调用Service

   

复制代码
 1 package Controllers;
 2 
 3 import Entity.Student;
 4 import Service.IStudentService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RestController;
 9 
10 import java.util.List;
11 
12 @RestController
13 @RequestMapping("/api/Student")
14 public class StudentController {
15     @Autowired
16     private IStudentService service;
17 
18     @GetMapping()
19     public String Get() {
20         List<Student> students = service.selectByCondition(new Student());
21         String jsonResult = com.alibaba.fastjson.JSON.toJSONString(students);
22         return jsonResult;
23     }
24 }
复制代码

  走到这一步的代码目录结构是这样子的:

  

  如果进行顺利的话,我们运行我们的Tomacat服务器,并调用我们的新接口:http://localhost:8080/api/Student

  运行时候,别忘记了修改jdbc.properties文件里的连接url以及用户名密码!!!

  

  

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

  

  还不快去添加几条数据调用一下试试嘛~