手把手教你整合 SpringMvc+Spring+MyBatis+Maven

注:该教程是参考孙宇老师的《SpringMvc+Spring+Mybatis+Maven整合视频教程1》整理的,花了我六个多小时,边复习视频边调代码边写教程,保证该教程每一步都能正确执行,以免给认真对待该教程的读者造成困扰,完整源码可以到 http://download.csdn.net/detail/taojiahuanjia/9043203 下载。

 

一、软件环境

操作系统:Windows 7

数据库:MySQL Community Server 5.6.17,MySQL 客户端使用 SQLyog 即可。

开发语言:Java,JDK1.8

开发环境:STS(Spring Tool Suite)3.7.0.RELEASE

软件版本:Spring-core 4.2.0.RELEASE,Mybatis 3.3.0,Mybatis-Spring 1.2.3(都是在 http://search.maven.org/ 查到的最新版本) 

二、生成测试数据库及表

在 SQLyog 中执行 SQL 语句。在本例中我们只会用到 forum 的 user 表。

/*
SQLyog Ultimate v11.24 (32 bit)
MySQL - 5.6.17 : Database - forum
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`forum` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `forum`;

/*Table structure for table `manager` */

DROP TABLE IF EXISTS `manager`;

CREATE TABLE `manager` (
  `managerId` int(11) NOT NULL AUTO_INCREMENT,
  `managerName` varchar(16) CHARACTER SET gb2312 NOT NULL,
  `managerPassword` varchar(12) CHARACTER SET gb2312 NOT NULL,
  PRIMARY KEY (`managerId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

/*Data for the table `manager` */

insert  into `manager`(`managerId`,`managerName`,`managerPassword`) values (1,'admin','admin');

/*Table structure for table `post` */

DROP TABLE IF EXISTS `post`;

CREATE TABLE `post` (
  `postId` int(11) NOT NULL AUTO_INCREMENT,
  `userId` int(11) NOT NULL,
  `topic` varchar(100) CHARACTER SET gb2312 NOT NULL,
  `matter` varchar(1000) CHARACTER SET gb2312 NOT NULL,
  `postTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`postId`)
) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8;

/*Data for the table `post` */

insert  into `post`(`postId`,`userId`,`topic`,`matter`,`postTime`) values (12,1,'不要问我为什么迟到','\r\n不要问我为什么迟到?\r\n\r\n我也不过是茫茫红尘中一粒浮尘而已,这个世界上有很多东西我无法解释!','2009-03-23 15:16:36'),(13,1,'我是一滴远方孤星的泪水','藏在你身上已几万年!所有你的心事都被我发现,让我温暖你的脸!\r\n','2009-03-19 09:45:14'),(14,1,'不要问我,一生曾经恨过多少人','    你不懂我恨有多深!\r\n哎!这是为什么呢!','2009-03-19 10:24:01'),(15,1,'有过多少往事','仿佛就在昨天!','2009-03-19 10:59:54'),(16,2,'雪花飘','雪花飘,飘起了多少爱恋。雪花飞,飞起了多少情缘。烟花开在雪中间!','2009-03-23 15:36:24'),(17,2,'在那遥远的小山村','在那遥远的小山村,小呀小山村!','2009-03-23 15:35:24'),(18,1,'等了好久终于等到今天','等了好久终于把梦实现,前途茫茫任我闯,幸亏还有你,在身旁!','2009-03-23 15:34:10'),(19,1,'曾经年少爱追梦','一心只想入前飞,行遍千山和万水,一路走来不能回!','2009-03-23 15:33:24'),(20,1,'如果有一天','如果有一天,汽车与飞机再不足够,别害怕,你拥有的,天赋的,一对双脚伴你可漫游!','2009-03-19 17:05:26'),(21,1,'难道','难道,出生当天我已给归类做坏人。难道,爱我会毁了你一生!','2009-03-19 17:06:32'),(22,1,'爱火烧不尽','爱火为你烧呀烧不尽,泪水为你一生流也流不停!','2009-03-23 15:13:57'),(23,1,'爱你等你到最后','虽然我知道你心中从不曾爱过我,对你没有怨尤,能够陪在你的左右,做痴心的朋友,也是一种快乐!','2009-03-19 17:11:34'),(24,1,'给我一点时间','给我一点时间,我可以吃光整个地球!','2009-03-23 15:15:30'),(48,1,'我有一个梦','我有一个梦,梦见我来生,是一个很有钱的人!','2009-03-23 15:15:46'),(50,1,'为什么迟到的总是你',' 今天堵车了,我上车的时候才8:29,还没到8:30上班时间。','2009-03-20 10:16:40'),(51,1,'浪子心声','难分真与假,人面多险诈,几许有共享荣华,檐畔水滴不分差。\r\n无知井里蛙,徒望添声价,空得意目光如麻,谁料金屋变败瓦。\r\n命里有时终须有,命里无时莫强求!\r\n雷声风雨打,何用多惊怕,心公正白璧无瑕,行善积德最乐也。\r\n命里有时终须有,命里无时莫强求!\r\n人比海里沙,何用多牵挂,君可见漫天落霞,名利息间似雾化!','2009-03-23 16:04:16'),(52,1,'跟我两辈子','你可否啊,跟我一辈子啊,把那昨天的恩和怨,丢进东江水啊。\r\n你可否啊,跟我一辈子啊,不再夜里空守在孤灯旁呀,跟我去个好地方!','2009-03-23 15:29:53');

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(16) CHARACTER SET gb2312 NOT NULL,
  `userPassword` varchar(12) CHARACTER SET gb2312 NOT NULL,
  `userEmail` varchar(100) CHARACTER SET gb2312 NOT NULL,
  `userNickname` varchar(20) CHARACTER SET gb2312 NOT NULL,
  `userBirthday` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `sex` int(11) NOT NULL,
  `userPoints` int(11) NOT NULL,
  `userRemark` varchar(200) CHARACTER SET gb2312 DEFAULT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`userId`,`userName`,`userPassword`,`userEmail`,`userNickname`,`userBirthday`,`sex`,`userPoints`,`userRemark`) values (1,'xiaoqi','xiaoqi0101','[email protected]','小起','1985-09-01 00:00:00',1,102,'为什么!'),(2,'xiaoxue','010101','[email protected]','小雪','1985-01-24 00:00:00',2,12,'雪花飘'),(3,'asdasd','asdasd','[email protected]','asdasd','2008-03-17 00:00:00',1,0,NULL);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
View Code

三、MyBatis Generator 生成代码

1、下载 MyBatis Generator:http://download.csdn.net/detail/u012909091/7206091 。(尝试过到官网下载,不过没找到 jar 文件。在 https://github.com/mybatis/generator 的底部有到 search.maven.org 的链接,然后点开 POM 中的 url ,发现被墙了。。)

2、解压 mybatis-generator-core-1.3.2.zip,注意不要放在含中文路径的目录下,本例中是放在 E:\springmvc\tools\ 下。清空 mybatis-generator-core-1.3.2\lib\src 目录。

3、修改 mybatis-generator-core-1.3.2\lib\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>
    
    
    <classPathEntry location="E:\springmvc\tools\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        commentGenerator>
        
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/forum" userId="root" password="sa">
        jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        javaTypeResolver>
        
        <javaModelGenerator targetPackage="sy.model" targetProject="E:\springmvc\tools\mybatis-generator-core-1.3.2\lib\src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="sy.mapping" targetProject="E:\springmvc\tools\mybatis-generator-core-1.3.2\lib\src">
            <property name="enableSubPackages" value="true" />
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="E:\springmvc\tools\mybatis-generator-core-1.3.2\lib\src">
            <property name="enableSubPackages" value="true" />
        javaClientGenerator>
        
        <table tableName="manager" domainObjectName="Manager" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <table tableName="post" domainObjectName="Post" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    context>
generatorConfiguration>
View Code

4、在 lib 目录,按住 shift 键——>鼠标右键——>在此处打开命令窗口——>执行以下命令。

java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite

手把手教你整合 SpringMvc+Spring+MyBatis+Maven_第1张图片

5、至此,Dao、Model、Mapping 相关文件已生成在 src 目录。

四、框架整合

1、打开 STS——File——New——Maven Project——Next——Filter输入webapp,选择maven-archetype-webapp,Next——Group Id输入sy.mybatistest,Artifact Id输入mybatistest,Package清空——Finish。

2、右键 mybatistest——Properties——Resource——Text file encoding,选择 Other:UTF-8,OK。

3、右键 mybatistest——Properties——Project Facets——Java 的 Version 改为 1.8,OK。

4、右键 mybatistest——Properties——Java Build Path——Library——选择JRE System Library [Java SE 1.8],Edit——选择 Workspace default JRE(jdk-1.8.0_05),Finish。这一步主要为了解决 STS 的一个bug,即工程创建后不显示 src/main/java 的问题,这样修改后可以看到显示出了这个文件夹。

5、引入 Spring 和 Mybatis 需要的包,浏览器打开 http://search.maven.org/ ,分别搜 spring-core、spring-webmvc、spring-tx、spring-jdbc、org.aspectj、mybatis、mybatis-spring、mysql-connector-java、junit、druid、jackson-mapper-asl(如果version1.9.13报错,就改成1.9.12)、commons-fileupload、jackson-core、jackson-databind,从结果列表中选择最新版本,把 Dependency Information 的 Apache Maven 信息拷贝到项目 pom.xml 文件 dependencies 中,在 junit 下需添加作用域 test 这样该包就只是在测试时使用,在发布生成war包时就不会包含该包。快捷键 ctrl+shift+f 将 pom.xml 代码格式化,缩进使代码看起来更舒服。

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.0modelVersion>
    <groupId>sy.mybatistestgroupId>
    <artifactId>mybatistestartifactId>
    <packaging>warpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>mybatistest Maven Webappname>
    <url>http://maven.apache.orgurl>
    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>4.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>4.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>4.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.8.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.3.0version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.3version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.36version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.15version>
        dependency>
        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.12version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.6.1version>
        dependency>
    dependencies>
    <build>
        <finalName>mybatistestfinalName>
    build>
project>
View Code

6、把 spring 配置文件(config.properties、log4j.properties、spring-mvc.xml、spring-mybatis.xml、spring.xml)放在 src/main/resources 下。

config.properties:

validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/forum?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=sa

sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
View Code

log4j.properties:

log4j.rootLogger=DEBUG,Console,File

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c]%m%n

log4j.appender.File=org.apache.log4j.RollingFileAppender 
log4j.appender.File.File=mybatis.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
View Code

spring-mvc.xml:

"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    
    
    id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        "supportedMediaTypes">
            
                text/html;charset=UTF-8
            
        
    

    
    "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        "messageConverters">
            
                "mappingJackson2HttpMessageConverter" />
            
        
    

    
    "org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

    id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        "defaultEncoding">
            UTF-8
        
        "maxUploadSize">
            32505856
        
        "maxInMemorySize">
            4096
        
    
    
    
    "sy.controller" />

View Code

spring-mybatis.xml:

"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
">

    
    

    
    "dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        "url" value="${jdbc_url}" />
        "username" value="${jdbc_username}" />
        "password" value="${jdbc_password}" />

        
        "initialSize" value="0" />
        
        "maxActive" value="20" />
        
        "maxIdle" value="20" />
        
        "minIdle" value="0" />
        
        "maxWait" value="60000" />

        

        "validationQuery" value="${validationQuery}" />
        "testOnBorrow" value="false" />
        "testOnReturn" value="false" />
        "testWhileIdle" value="true" />

        
        "timeBetweenEvictionRunsMillis" value="60000" />
        
        "minEvictableIdleTimeMillis" value="25200000" />

        
        "removeAbandoned" value="true" />
        
        "removeAbandonedTimeout" value="1800" />
        
        "logAbandoned" value="true" />

        
        
        "filters" value="mergeStat" />
    

    
    id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        "dataSource" ref="dataSource" />
        
        "mapperLocations" value="classpath:sy/mapping/*.xml" />
    

    "org.mybatis.spring.mapper.MapperScannerConfigurer">
        "basePackage" value="sy.dao" />
        "sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    

    
    id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        "dataSource" ref="dataSource" />
    

    
    

    
    id="transactionAdvice" transaction-manager="transactionManager">
        
            "add*" propagation="REQUIRED" />
            "append*" propagation="REQUIRED" />
            "insert*" propagation="REQUIRED" />
            "save*" propagation="REQUIRED" />
            "update*" propagation="REQUIRED" />
            "modify*" propagation="REQUIRED" />
            "edit*" propagation="REQUIRED" />
            "delete*" propagation="REQUIRED" />
            "remove*" propagation="REQUIRED" />
            "repair" propagation="REQUIRED" />
            "delAndRepair" propagation="REQUIRED" />

            "get*" propagation="SUPPORTS" />
            "find*" propagation="SUPPORTS" />
            "load*" propagation="SUPPORTS" />
            "search*" propagation="SUPPORTS" />
            "datagrid*" propagation="SUPPORTS" />

            "*" propagation="SUPPORTS" />
        
    
    
        id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" />
        "transactionPointcut" advice-ref="transactionAdvice" />
    
View Code

spring.xml:

"1.0" encoding="UTF-8"?>
"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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
">

    
    "classpath:config.properties" />

    
    "sy.service" />


View Code

7、复制第二步生成的 src 目录下的 sy 文件夹到项目 src/main/java 下。

8、在 src/main/java 目录下新建 package:sy.service。在该包下新建接口 UserServiceI。

package sy.service;

import sy.model.User;

public interface UserServiceI {    
    
    public User getUserById(Integer id);

}

9、在 sy.service 下新建类 UserServiceImpl 实现接口 UserServiceI。定义成员变量 userMapper,并生成 getter 和 setter(alt+shift+s——>Generate Getters and Setters)。

package sy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sy.dao.UserMapper;
import sy.model.User;

@Service("userService")
public class UserServiceImpl implements UserServiceI {
    
    private UserMapper userMapper;

    public UserMapper getUserMapper() {
        return userMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getUserById(Integer id) {
        // TODO Auto-generated method stub
        return userMapper.selectByPrimaryKey(id);
    }

}

10、在 src/test/java 下新建类 TestMybatis,包名为 sy.test。 

package sy.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import sy.model.User;
import sy.service.UserServiceI;

public class TestMybatis {

    private ApplicationContext ac;
    private UserServiceI userService;

    @Before
    public void Before() {
        ac = new ClassPathXmlApplicationContext(new String[] { "spring.xml",
                "spring-mybatis.xml" });
        userService = (UserServiceI) ac.getBean("userService");
    }

    @Test
    public void test1() {
        User u = userService.getUserById(1);
        System.out.println(u.getUsername());
    }
    
    @Test
    public void test2() {
    }

}

11、选中 TestMybatis.java 文件,右键——Run As——Junit Test,如果成功会在 Console 中输出结果,失败的话在 Junit 下会看到错误信息,多半是因为缺 jar 包。

12、以上是使用 Junit 测试,下面我们使用 Spring 测试。

13、在 pom.xml 中添加 spring-test 依赖。修改 TestMybatis.java 文件。 

package sy.test;

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

import sy.model.User;
import sy.service.UserServiceI;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring.xml","classpath:spring-mybatis.xml"})
public class TestMybatis {
    
    private UserServiceI userService;
    
    public UserServiceI getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }

    @Test
    public void test1(){        
        User u=userService.getUserById(2);
        System.out.println(u.getUsername());
    }

}
View Code

14、选中 TestMybatis.java 文件,右键——Run As——Junit Test,输出结果即成功。

15、下面开始 Spring MVC 的整合。

16、在 src/main/java 目录下新建 package:sy.controller。在该包下新建类 UserController。 

package sy.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import sy.model.User;
import sy.service.UserServiceI;

@Controller
@RequestMapping("/userController")
public class UserController {
    
    private UserServiceI userService;
    
    public UserServiceI getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }

    @RequestMapping("/showUser")
    public String showUser(String id,HttpServletRequest request){
        User u=userService.getUserById(Integer.valueOf(id));
        request.setAttribute("user", u);
        return "showUser";
    }

}

 

17、修改 src/main/webapp/WEB-INF/web.xml:

xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <mvc:default-servlet-handler/>
    <display-name>mybatisdisplay-name>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xmlparam-value>
    context-param>
    <filter>
        <description>字符集过滤器description>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <description>字符集编码description>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    <listener>
        <description>spring监听器description>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>
    
    <servlet>
        <description>spring mvc servletdescription>
        <servlet-name>springMvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <description>spring mvc 配置文件description>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springMvcservlet-name>
        <url-pattern>*.dourl-pattern>
    servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jspwelcome-file>
    welcome-file-list>
    
    <session-config>
        <session-timeout>15session-timeout>
    session-config>
web-app>
View Code

18、在 src/main/webapp/ 下新建 showUser.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>${user.username}
body>
html>
View Code

19、右键工程——Run AS——Maven install。

20、右键工程——Run AS——Run on Server——选择 Tomcat,Next——将 mybatistest 选到右边——Finish。

21、输入网址:http://localhost:8081/mybatistest/userController/showUser.do?id=1 ,网页显示出查询结果。

22、想要使用另一种 URL 访问,就要修改 UserController.java 文件。

URL:http://localhost:8081/mybatistest/userController/showUser/1.do

package sy.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import sy.model.User;
import sy.service.UserServiceI;

@Controller
@RequestMapping("/userController")
public class UserController {
    
    private UserServiceI userService;
    
    public UserServiceI getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }

    @RequestMapping("/showUser/{id}")
    public String showUser(@PathVariable String id,HttpServletRequest request){
        User u=userService.getUserById(Integer.valueOf(id));
        request.setAttribute("user", u);
        return "showUser";
    }

}
View Code

23、全部结束。感谢孙宇老师的视频教程!

手把手教你整合 SpringMvc+Spring+MyBatis+Maven_第2张图片

 

参考资料:

1. BBS.BTBOYS.COM社区-孙宇. 《SpringMvc+Spring+Mybatis+Maven整合视频教程1》

转载于:https://www.cnblogs.com/NaughtyBaby/p/4754881.html

你可能感兴趣的:(java,测试,数据库)