一、软件环境
操作系统: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 表。
三、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="D:\software\lib\mysql-connector-java-5.1.21.jar" /> --> <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> <!-- 数据库链接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\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> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="sy.dao" targetProject="E:\springmvc\tools\mybatis-generator-core-1.3.2\lib\src"> <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:
log4j.properties:
spring-mvc.xml:
spring-mybatis.xml:
spring.xml:
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 文件。
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:
18、在 src/main/webapp/ 下新建 showUser.jsp:
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"; } }