快速搭建SSM(Spring,SpringMVC,Mybatis)环境详细过程

快速搭建SSM(Spring,SpringMVC,Mybatis)环境详细过程
我是做移动(Android)开发的,这几天利用项目空隙大概学习了数据接口的相关知识,在这里主要记录一下搭建SSM环境的操作过程。所谓“工欲善其事必先利其器”,搭建开发环境往往是学习的第一步,其实这么说不太准确,选择使用什么环境才是最先应该考虑的,暂时叫做第零步吧。

快速搭建SSMSpringSpringMVCMybatis环境详细过程
第零步 选择环境
1 选择语言
2 选择编译器
3 选择框架
第一步 搭建环境
11 版本说明
2 环境初始化
21 安装tomcat
22 为eclipse配置tomcat
3 创建项目
31 新建MAVEN项目
32 为项目添加运行环境
33 同步版本信息
4 搭建框架
41 添加依赖
42 做必要配置
43 添加Spring配置文件
44 创建数据库属性文件
45 创建SpringMVC配置文件
46 创建mybatis配置文件
第二步 测试环境
1 测试Sring MVC
11 创建bean
12 创建controller
13 运行项目
2 测试mybatis
21 构建MBG逆向工程
211 准备数据库环境
212 创建MBG配置文件
213 实现逆向工程
22 进行单元测试
第零步 选择环境
0.1 选择语言
据我所知,php,python和java等都可以用作后台开发,相对其他两门语言,我对java比较熟悉,所以优先考虑使用java. 
对于还没有下载安装jdk朋友,可以根据我下面提供的两个链接下载和安装。 
Java SE Development Kit 8 Downloads 
安装教程 
这里的下载链接是oracle官方网站,可放心下载。安装教程是我两年前写的一个博文,基本流程没有变化,大家凑合看吧。

0.2 选择编译器
对于java开发,我经常使用的编译器有myeclipse,eclipse,idea等,碍于myeclipse和idea的版权问题,我选择的编译器是eclipse oxygen. 
Eclipse IDE for Java EE Developers 
eclipse是免安装的,直接解压一下就能使用。我建议安装路径和工作空间(workspace)尽量放在全英文无空格的路径下,这样可以省去好多麻烦。

0.3 选择框架
虽然已经无数次调用过数据接口了,但是对于如何开发接口,要用到哪方面的知识,我是一脸懵逼。我阅读了好多大神的博客,他们的说法和做法各有不同,看起来每个方法都可以,但是都不够详细。最后请教我们的接口妹子,她给了我一套项目源码让我参考学习,我以为通过看源码所有的困惑都可以解开了,然后一切才刚刚开始。 
项目没有想象中的那么简单,代码业务倒很简单,MVC开发模式我也看得懂。但是几乎每个类,每个方法,每个字段上面都有注解,而且这些注解都是我之前没有见过的,果断“刨根究底,追根溯源”,原来这就是ssm(Spring,SpringMVC,Mybatis)框架,网上早有各路大神著书立言了。既然知道“是什么”了,接下来要解决的问题就是“怎么做”了。

第一步 搭建环境
3.1.1 版本说明
操作系统:windows10专业版
jdk:1.8.0_144
eclipse:oxygen
服务器:tomcat 9.0
数据库:mysql 5.7.18
1.2 环境初始化
1.2.1 安装tomcat
下载Apache Tomcat® 
安装教程 
安装教程只看“安装配置Tomcat”部分就可以了。

1.2.2 为eclipse配置tomcat

如图单击Window-Preferences 
 
单击Server-Runtime Environment-Add 
 
选择Apache Tomcat v9.0然后单击next 
 
tomcat installation directory为tomcat的安装路径 
 
单击apply and close

1.3 创建项目
1.3.1 新建MAVEN项目

在菜单栏依次单击File-New-Maven Project 
 
选择maven-archetype-webapp,然后单击next; 
填写Group Id,Artifact Id,Package,单击Finish,稍等片刻。 

到这里项目创建完成了,但是项目节点上有个红叉叉,同时Markers中报错说找不到HttpServlet这个父类,下面我们解决一下。

1.3.2 为项目添加运行环境
 
在项目节点右键,然后依次单击Build Path-Configure Build Path…,打开Java Build Path,切换到Libraries标签, 
 
单击Add Library按钮; 
 
在Add Library选择Server Runtime并单击Next; 
 
如果1.2.2配置没有问题的话会列出已经添加的server runtime,选择之后单击Finish. 

可以看到Apache Tomcat已经添加进来了,其他选项暂时不用管,一会儿我会讲到。单击apply and close应用并关闭该界面。

1.3.3 同步版本信息

在菜单来中依次点击Window-Show View-Navigator,打开Navigator. 

跳到Navigator标签。 

在.settings文件夹下打开org.eclipse.jdt.core.prefs,将红色框中的参数修改为图中所示的数据,并保存文件。 

打开org.eclipse.wst.common.component,将红色框中的参数修改为图中所示的数据,并保存文件。 

打开org.eclipse.wst.common.project.facet.core.xml,将红色框中的参数修改为图中所示的数据,并保存文件。 

删除如图目录下web.xml(后提到该文件指如图目录下)中红色框中内容,警告信息暂时不用管。 

按照1.3.2中提到的步骤修改JRE System Library为JavaSE-1.8. 

打开项目根节点下的pom.xml,添改如下代码。

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <!-- 指定source和target的版本 -->
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

在项目节点右击,依次单击Maven-Update Project, 
 
勾选当前的项目,单击OK按钮。稍等片刻,项目中的红色叉叉应该会消失。如果没有消失再详细检查一下前面的所有步骤,然后看一下Markers中的错误。

1.4 搭建框架
确保前面所有的步骤都没有问题之后,开始搭建框架了。我学习这部分的时候,主要看了网易云课堂雷老师的《SSM高级整合视频教程》,在这里对雷老师表示衷心的感谢。 
由于这篇博客的主题是搭建过程,我主要从实用的角度出发,主要讲解搭建步骤,几乎不会讲解为什么要这么做。

1.4.1 添加依赖
打开项目根目录下的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>cn.stevengo</groupId>
    <artifactId>ssm-test</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ssm-test Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <!--spring控制模块 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.13.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!-- mybatis整合spring的适配包 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

        <!-- 数据库连接池 -->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!-- 数据库驱动 -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <!-- jstl -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- servlet api -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

        <!-- junit -->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <!-- 指定source和target的版本 -->
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
1.4.2 做必要配置
修改web.xml的信息,添加spring容器,前端控制器,字符编码控制器等,修改后代码如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<web-app  version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
     <!-- 启动spring的容器 -->   
     <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>
   <!-- Spring MVC的前端控制器 -->
    <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:SpringMVC-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 字符编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResposeEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 使用rest风格的URI -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <display-name>Archetype Created Web Application</display-name>

</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
1.4.3 添加Spring配置文件
在src\main\resources目录下新建名为applicationContext.xml的文件(注意:文件名和文件路径与web.xml中的配置有关,不要修改),添加如下代码,注意将代码中的包名修改为设置的。同时在该目录下创建名为mapper的文件夹,用来保存数据库映射文件。

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-4.3.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <context:component-scan base-package="cn.stevengo">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!--sping的配置文件和业务逻辑有关的 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!-- 配置和mybatis的整合 -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <!-- 指定mybatis mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!-- 配置扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描素有的dao接口的实现,加入到容器中 -->
        <property name="basePackage" value="cn.stevengo.ssmtest.dao"></property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="pooledDataSource"></property>
    </bean>
    <!-- 开启基于注解的事务 -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* cn.stevengo.ssmtest.service..*(..))"
            id="txPoint"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
    </aop:config>
    <!-- 配置事务增强 -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*" />
            <tx:method name="get*" read-only="true" />
        </tx:attributes>
    </tx:advice>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
1.4.4 创建数据库属性文件
在src\main\resources创建文件名为jdbc.properties的文件,内容格式如下。注意url,driver,user,password都是自己在数据库设置的信息。

jdbc.url=jdbc:mysql://localhost:3306/testDB?useUnicode=true&characterEncoding=utf-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=testUser
jdbc.password=123456
1
2
3
4
1.4.5 创建SpringMVC配置文件
在src\main\resources创建文件名为SpringMVC-servlet.xml的文件。因为我创建的项目的主要目的是为移动端写数据接口,在mvc:annotation-driven中配置了阿里巴巴的fastJson,可以将实体以json的形式返回。在

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-4.3.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- spring MVC配置,包含网站跳转逻辑的控制,配置 -->
    <context:component-scan base-package="cn.stevengo"
        use-default-filters="false">
        <!-- 只扫描控制器 -->
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>
    <!-- 定义无Controller的path<->view直接映射 -->
    <!-- 定义视图文件解析 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
    <mvc:default-servlet-handler />
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <bean
                class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 避免IE返回时出现下载提示! -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1.4.6 创建mybatis配置文件
在src\main\resources创建文件名为mybatis-config.xml的文件,配置信息如下,注意将包名替换为自己的。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    <typeAliases>
        <package name="cn.stevengo.ssmtest.bean" />
    </typeAliases>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
 
配置完成之后目录结构如图所以,大家对照看一下自己文件的位置有没有放错。然后执行依次update Project,看看项目有没有红叉叉,如果出现了对照错误信息看看哪一个环节出现问题了。 
 
如果没有问题,运行一次项目,看看能不能出来hello world. 

如果看到这个界面,说明环境已经搭建完成了。

第二步 测试环境
关于环境的测试,主要分为两个部分,第一是Spring MVC,第二是mybatis.创建包结构如下: 


2.1 测试Sring MVC
2.1.1 创建bean
在cn.stevengo.ssmtest.bean中创建TestBean.java.内容如下:

package cn.stevengo.ssmtest.bean;

/**
 * 用于测试的bean
 */
public class TestBean {
    private String testStr;
    private int testInt;

    public String getTestStr() {
        return testStr;
    }

    public void setTestStr(String testStr) {
        this.testStr = testStr;
    }

    public int getTestInt() {
        return testInt;
    }

    public void setTestInt(int testInt) {
        this.testInt = testInt;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2.1.2 创建controller
在cn.stevengo.controller创建TestController.java,内容如下:

package cn.stevengo.ssmtest.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stevengo.ssmtest.bean.TestBean;

@Controller
public class TestController {
    @RequestMapping("stringTest")
    @ResponseBody
    public String returnStr() {
        return "hello,即使是中文也可以";
    }

    @RequestMapping("entityTest")
    @ResponseBody
    public TestBean returnEntify() {
        TestBean testBean = new TestBean();
        testBean.setTestStr("测试实体");
        testBean.setTestInt(12);
        return testBean;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2.1.3 运行项目
在地址栏输入:http://localhost:8080/ssm-test/stringTest,返回输入如下: 
 
在地址栏输入:http://localhost:8080/ssm-test/entityTest,返回输入如下: 
 
如果数据返回正常,说明环境spring MVC环境正常。

2.2 测试mybatis
对于这部分的处理,我的策略是首先用MyBatis Generator(MBG)逆向工程生成bean,dao和mapper,然后用junit单元测试完成。

2.2.1 构建MBG逆向工程
2.2.1.1 准备数据库环境
创建数据库和对应的表,我这里的数据库名为testDB,数据表为test_t,表中有两个字段,分表是testStr,testInt,分别代表整型和字符串类型的数据。由于表结构非常简单,这里不再演示创建过程了。

2.2.1.2 创建MBG配置文件
在项目根目录下创建名为generatorConfig.xml的文件,其内容如下所示

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!-- 禁止添加注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/testDB"
            userId="testUser" password="123456">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 指定javabean生成的位置 -->
        <javaModelGenerator targetPackage="cn.stevengo.ssmtest.bean"
            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 指定映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 指定dao接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="cn.stevengo.ssmtest.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <table tableName="test_t" domainObjectName="TestBean"></table>
    </context>
</generatorConfiguration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2.2.1.3 实现逆向工程
在cn.stevengo.ssmtest.test创建名为MBGTest.java的文件,其内容如下所示:

package cn.stevengo.ssmtest.test;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MBGTest {
    public static void main(String args[])
            throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
           List<String> warnings = new ArrayList<String>();
           boolean overwrite = true;
           File configFile = new File("generatorConfig.xml");
           ConfigurationParser cp = new ConfigurationParser(warnings);
           Configuration config = cp.parseConfiguration(configFile);
           DefaultShellCallback callback = new DefaultShellCallback(overwrite);
           MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
           myBatisGenerator.generate(null);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
在该文件上右击,然后以java application的方式运行。运行完之后刷新项目列表,此对应的包下面生成了包文件(注意上一个测试可能由于bean结构的变化失效,此时修改controller的代码即可),结果如图所示: 


2.2.2 进行单元测试
生成的文件mapper文件和dao接口提供了好多方法我们只对其中插入进行测试。 
在在cn.stevengo.ssmtest.test创建名为TestDao.java的文件,其内容如下所示:

package cn.stevengo.ssmtest.test;

import org.junit.runner.RunWith;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.stevengo.ssmtest.bean.TestBean;
import cn.stevengo.ssmtest.dao.TestBeanMapper;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class TestDao {
    @Autowired
    TestBeanMapper testBeanMapper;

    @Test
    public void testInsert() {
        TestBean testBean = new TestBean();
        testBean.setTeststr("mybatisInsert");
        testBean.setTestint(343);

        testBeanMapper.insert(testBean);

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
以junit运行上述代码,待完成之后打开数据库,检查记录是否已经插入。 
至此,SSM环境的搭建与测试已经完全完成了,你是不是已经学会了呢? 
码字不易,如果有朋友想要转载,烦请注明出处: 
http://blog.csdn.net/u010378929/article/details/79057872 
如果在阅读的过程中遇到了问题,可以评论区回复或者将问题发到我的邮箱1435374903@qq.com.我会及时处理。
————————————————
版权声明:本文为CSDN博主「Steven Go」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010378929/article/details/79057872

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值