最近看见网上整理的Spring+SpringMVC+MyBatis+Maven太low,正好今天有时间,于是整理了下,那么开始吧!
1、使用的工具
- STS下载地址
http://www.springsource.org/downloads/sts-ggts
- Tomcat
- JDK
- Mybatis generator
-
若使用Eclipse开发(需要配置Maven,Maven配置好后,在命令行下输入mvn -v,显示下图代表配置成功)
2、Generator的结构
- 首先得有数据库表
- src文件夹为生成模型的位置(dao,mapping,model)
-
generator.xml配置
- mybatis-generator-core-1.3.2.jar核心包
- 生成语句复制,右键在此处打开命令行(注意路径不能用中文)
-
生成结果如下图所示
3、打开Eclipse新建Maven项目
- 如图红色箭头所示,选择默认的空间,next
- 最后Finish
- 最后生成项目结构如下图所示
- 项目建立后,首先我会把编码改成utf-8,省的以后有麻烦。
- 你会发现项目目录没有显示出来,那么我们选择属性如图
- 这时你会发现目录还是没有变化,那么接下来我们在调试,默认是J2SE-1.5
- 那么我们在编辑指定一下它,如图
- 这时在回过头来看项目目录,以完整。
4、项目建立完毕,引入Spring和MyBatis需要的jar包
- 打开pom.xml
- 如果引入的时候,记不住groupId和版本号,其实在Eclipse里面有一个如图所示,当然这种方法不好(请看下一种)
- 那么我们选择手写,打开浏览器输入
http://search.maven.org/
- 记住spring核心包spring-core
- mybatis
- mybatis-spring
- mysql-connector-java
- junit
- 数据源druid
- org.aspectj
- 记住后面还有jar包需要加入
pom.xml代码
4.0.0
dc_zaichi.mybatis
mybatis
war
0.0.1-SNAPSHOT
mybatis Maven Webapp
http://maven.apache.org
org.springframework
spring-test
3.2.0.RELEASE
org.springframework
spring-webmvc
3.2.0.RELEASE
org.springframework
spring-core
3.2.0.RELEASE
org.mybatis
mybatis
3.1.1
org.mybatis
mybatis-spring
1.1.1
mysql
mysql-connector-java
5.1.21
junit
junit
4.11
test
com.alibaba
druid
0.2.9
org.aspectj
aspectjweaver
1.7.1
org.codehaus.jackson
jackson-mapper-asl
1.9.11
commons-fileupload
commons-fileupload
1.2.2
javax.servlet
servlet-api
3.0-alpha-1
log4j
log4j
1.2.17
com.alibaba
fastjson
1.1.26
5、配置文件
- spring
- spring-mybatis
dc_zaichi.service.*
- 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
- config.properties配置文件
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=sypro
#jdbc_password=sypro
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/dc_zaichi?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=helei
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=sypro
#jdbc_password=sypro
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=true
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
6、这样我们已经将Spring和mybatis完全整合了,接下来上代码
- 写接口,查询一个资产,肯定要返回一个Asset_Check
package dc_zaichi.service;
import dc_zaichi.model.Asset_Check;
public interface AssetCheckService {
public Asset_Check getAssetCheckById(String id);
}
- 接下来写实现类
package dc_zaichi.service.Impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import dc_zaichi.dao.Asset_CheckMapper;
import dc_zaichi.model.Asset_Check;
import dc_zaichi.service.AssetCheckService;
//AssetCheckServiceImpl把他放到spring上下文环境中
@Service("AssetCheckService")
public class AssetCheckServiceImpl implements AssetCheckService{
//AssetCheckServiceImpl处理业务逻辑后,业务逻辑调用数据库,就是dao,也就是mappper,要使用这个mapper,一定要通过spring注入,首先要有get和set方法,那么如何将Asset_CheckMapper 注入到services里面呢?在set方法上加@Autowired注解
//当然了,这个service还是一个普通的类,因为没有放到spring上下文环境当中,自动扫描包后需要一个serviced的注解告诉扫描的那个地方,这个类是一个bean。这样spring上下文在启动的时候,就能加入到spring环境当中了
private Asset_CheckMapper asset_CheckMapper;
public Asset_CheckMapper getAsset_CheckMapper() {
return asset_CheckMapper;
}
//
@Autowired
public void setAsset_CheckMapper(Asset_CheckMapper asset_CheckMapper) {
this.asset_CheckMapper = asset_CheckMapper;
}
public Asset_Check getAssetCheckById(String id) {
// TODO Auto-generated method stub
return asset_CheckMapper.selectByPrimaryKey(id);
}
}
7、测试,因为是Maven项目, 在src/test/java目录下建立包名和测试类,通过junit测试
package mybatis.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dc_zaichi.model.Asset_Check;
import dc_zaichi.service.AssetCheckService;
public class TestMyBatis {
@Test
public void test1(){
ApplicationContext ac=
new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
AssetCheckService bean = (AssetCheckService) ac.getBean("AssetCheckService");
//这个bean就是实现类中的那个service注解
Asset_Check assetCheckById = bean.getAssetCheckById("1");
System.out.println(assetCheckById.getAcName());
}
}
- 打印如下
8、设想下,测试类中有一个测试方法我们可以这样写, 如果有100个测试方法,那么这个速度难以忍受,因为spring在初始化的时候,即耗资源又耗时间。那么我们可以这样写
package mybatis.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dc_zaichi.model.Asset_Check;
import dc_zaichi.service.AssetCheckService;
public class TestMyBatis {
private ApplicationContext ac;
AssetCheckService bean;
@Before
public void before(){
ac=new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
bean = (AssetCheckService) ac.getBean("AssetCheckService");
}
@Test
public void test1(){
Asset_Check assetCheckById = bean.getAssetCheckById("1");
System.out.println(assetCheckById.getAcName());
}
}
@Before的作用:在当前这个类所有测试方法之前去执行的这么一个方法。将所有初始化的东西放到这个放到这个方法之内。那么只会执行一次
到此,说明spring和mybatis整合成功
接下里再看一种测试方法:添加spring-test的jar包依赖
package mybatis.test;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import dc_zaichi.model.Asset_Check;
import dc_zaichi.service.AssetCheckService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
"classpath:spring-mybatis.xml" })
public class TestMyBatis {
private AssetCheckService assetCheckService;
public AssetCheckService getAssetCheckService() {
return assetCheckService;
}
@Autowired
public void setAssetCheckService(AssetCheckService assetCheckService) {
this.assetCheckService = assetCheckService;
}
// private ApplicationContext ac;
// AssetCheckService bean;
// @Before
// public void before(){
//
// ac=new ClassPathXmlApplicationContext(new
// String[]{"spring.xml","spring-mybatis.xml"});
// bean = (AssetCheckService) ac.getBean("AssetCheckService");
// }
//
@Test
public void test1() {
Asset_Check assetCheckById = assetCheckService.getAssetCheckById("1");
System.out.println(assetCheckById.getAcName());
}
}
ok
9、 导入springMVC的jar包,搜索spring-webmvc
- springMVC配置文件
text/html;charset=UTF-8
UTF-8
32505856
4096
- 接下来,我们建立一个包,和类如下图
- 建立Controller类如下图所示
package dc_zaichi.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import dc_zaichi.model.Asset_Check;
import dc_zaichi.service.AssetCheckService;
@Controller
// 加入到springmvc的上下文当中
@RequestMapping("/assetCheckController")
// 这个东西就是访问地址的一个配置
public class AssetCheckController {
// 比如说执行 http://127.0.0.1:8080/mybatis/assetCheckController.do 访问此控制器
private AssetCheckService assetCheckService;
public AssetCheckService getAssetCheckService() {
return assetCheckService;
}
@Autowired
public void setAssetCheckService(AssetCheckService assetCheckService) {
this.assetCheckService = assetCheckService;
}
@RequestMapping("/showAssetCheck")
public String showAssetCheck(String id, HttpServletRequest request) {
// http://localhost:8080/mybatis/assetCheckController.do?id=1
// 后台接的时候,接到这个id,并且去数据库查找这个资产,也就是AssetCheckController访问数据库,不能直接
// 访问,得通过业务逻辑service
// 访问此控制器里的一个方法
// http://127.0.0.1:8080/mybatis/assetCheckController.showAssetCheck.do
Asset_Check assetCheckById = assetCheckService.getAssetCheckById(id);
System.out.println(assetCheckById.getAcName());
// 把assetCheckById存到Request中
request.setAttribute("Asset_Check", assetCheckById);
return "showAssetCheck";// 返回一个jsp,不用howAssetCheck.jsp,已经在spring-mvc中配置好
}
}
如何启动SpringMVC,修改web.xml
mybatis
contextConfigLocation
classpath:spring.xml,classpath:spring-mybatis.xml
字符集过滤器
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
字符集编码
encoding
UTF-8
encodingFilter
/*
spring监听器
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
spring mvc servlet
springMvc
org.springframework.web.servlet.DispatcherServlet
spring mvc 配置文件
contextConfigLocation
classpath:spring-mvc.xml
1
springMvc
*.do
/index.jsp
15
10、页面
11、ok