最近看见网上整理的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代码
<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>dc_zaichi.mybatis</groupId>
<artifactId>mybatis</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.26</version>
</dependency>
</dependencies>
<build>
</build>
</project>
5、配置文件
- spring
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
<!-- 自动扫描(自动注入) -->
<context:component-scan base-package="dc_zaichi.service" />
</beans>
- spring-mybatis
<?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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.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:dc_zaichi/mapping/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dc_zaichi.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(* dc_zaichi.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
<!-- 配置druid监控spring jdbc -->
<bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
<property name="patterns">
<list>
<value>dc_zaichi.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
</aop:config>
</beans>
- 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配置文件
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="dc_zaichi.controller" />
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<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="mappingJacksonHttpMessageConverter" /><!-- 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>
</beans>
- 接下来,我们建立一个包,和类如下图
- 建立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
<?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">
<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>
10、页面
11、ok