注:该教程是参考孙宇老师的《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,'不要问我为什么迟到',' 不要问我为什么迟到? 我也不过是茫茫红尘中一粒浮尘而已,这个世界上有很多东西我无法解释!','2009-03-23 15:16:36'),(13,1,'我是一滴远方孤星的泪水','藏在你身上已几万年!所有你的心事都被我发现,让我温暖你的脸! ','2009-03-19 09:45:14'),(14,1,'不要问我,一生曾经恨过多少人',' 你不懂我恨有多深! 哎!这是为什么呢!','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,'浪子心声','难分真与假,人面多险诈,几许有共享荣华,檐畔水滴不分差。 无知井里蛙,徒望添声价,空得意目光如麻,谁料金屋变败瓦。 命里有时终须有,命里无时莫强求! 雷声风雨打,何用多惊怕,心公正白璧无瑕,行善积德最乐也。 命里有时终须有,命里无时莫强求! 人比海里沙,何用多牵挂,君可见漫天落霞,名利息间似雾化!','2009-03-23 16:04:16'),(52,1,'跟我两辈子','你可否啊,跟我一辈子啊,把那昨天的恩和怨,丢进东江水啊。 你可否啊,跟我一辈子啊,不再夜里空守在孤灯旁呀,跟我去个好地方!','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','xiaoqi@163.com','小起','1985-09-01 00:00:00',1,102,'为什么!'),(2,'xiaoxue','010101','xiaoqi@163.com','小雪','1985-01-24 00:00:00',2,12,'雪花飘'),(3,'asdasd','asdasd','xiaoqi@163.com','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 */;
三、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 ools 下。清空 mybatis-generator-core-1.3.2libsrc 目录。
3、修改 mybatis-generator-core-1.3.2libgeneratorConfig.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="D:softwarelibmysql-connector-java-5.1.21.jar" /> --> <classPathEntry location="E:springmvc oolsmybatis-generator-core-1.3.2libmysql-connector-java-5.1.25-bin.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- 数据库链接URL、用户名、密码 --> <!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sy" userId="sypro" password="sypro"> --> <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 oolsmybatis-generator-core-1.3.2libsrc"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的映射文件包名和位置 --> <sqlMapGenerator targetPackage="sy.mapping" targetProject="E:springmvc oolsmybatis-generator-core-1.3.2libsrc"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="E:springmvc oolsmybatis-generator-core-1.3.2libsrc"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(更改tableName和domainObjectName就可以) --> <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>
4、在 lib 目录,按住 shift 键——>鼠标右键——>在此处打开命令窗口——>执行以下命令。
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
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 下需添加作用域 <scope>test</scope> 这样该包就只是在测试时使用,在发布生成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.0</modelVersion> <groupId>sy.mybatistest</groupId> <artifactId>mybatistest</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mybatistest Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.0.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <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> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.15</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.12</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.1</version> </dependency> </dependencies> <build> <finalName>mybatistest</finalName> </build> </project>
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
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
spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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"> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /><!-- json转换器 --> </list> </property> </bean> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 --> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 --> <context:component-scan base-package="sy.controller" /> </beans>
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" 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 "> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- myBatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="mapperLocations" value="classpath:sy/mapping/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="sy.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
spring.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" 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 "> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 自动扫描(自动注入) --> <context:component-scan base-package="sy.service" /> </beans>
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()); } }
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>mybatis</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value> </context-param> <filter> <description>字符集过滤器</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集编码</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <description>spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- spring mvc servlet --> <servlet> <description>spring mvc servlet</description> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>spring mvc 配置文件</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 配置session超时时间,单位分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
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 here</title> </head> <body>${user.username} </body> </html>
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"; } }
23、全部结束。感谢孙宇老师的视频教程!
参考资料:
1. BBS.BTBOYS.COM社区-孙宇. 《SpringMvc+Spring+Mybatis+Maven整合视频教程1》