SSM 整合 以及 Ehcache 步骤

Spring 整合 MyBatis 整合步骤

 

1、建立工程,加入Spring和MyBatis的有关jar包

2、建立开发目录结构,创建实体类

3、创建访问数据接口

4、数据数据访问接口的实现类

5、配置SQL映射语句文件

6、配置Mybatis应用配置文件

7、配置Spring应用配置文件

 

---------------------------------------------

扫描二维码关注公众号,回复: 272881 查看本文章

配置

configuration 配置

properties 可以配置在Java 属性配置文件中

settings 修改 MyBatis 在运行时的行为方式

typeAliases 为 Java 类型命名一个别名(简称)

typeHandlers 类型处理器

objectFactory 对象工厂

plugins 插件

environments 环境

environment 环境变量

transactionManager 事务管理器

dataSource 数据源

 

mappers  映射器

-------------------------------------------------------

 

spring和springMVC和mybatis整合步骤

 

mybatis-config.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"  
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	
	<settings> 
        <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->   
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings>

	<typeAliases>
		<typeAlias type="com.fh.entity.system.User" alias="User"/>
		<typeAlias type="com.fh.entity.system.Role" alias="Role"/>
		<typeAlias type="com.fh.entity.system.Menu" alias="Menu"/>
		<typeAlias type="com.fh.util.PageData" alias="pd"/>
		<!-- 分页 -->
		<typeAlias type="com.fh.entity.Page" alias="Page"/>
	</typeAliases>
	
	<plugins>
		<plugin interceptor="com.fh.plugin.PagePlugin">
			<property name="dialect" value="mysql"/>
			<property name="pageSqlId" value=".*listPage.*"/>
		</plugin>
	</plugins>
	
</configuration>

 

 

AppalicationContext-mvc.xmv

<?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:mvc="http://www.springframework.org/schema/mvc"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
	<mvc:annotation-driven/>	
	<mvc:default-servlet-handler/>
	
	<context:component-scan base-package="com.fh.controller" />
	<context:component-scan base-package="com.json" />

	<!-- 对静态资源文件的访问  restful-->     
	<mvc:resources mapping="/admin/**" location="/,/admin/" />
	<mvc:resources mapping="/static/**" location="/,/static/" />
	<mvc:resources mapping="/plugins/**" location="/,/plugins/" />
	<mvc:resources mapping="/uploadFiles/**" location="/,/uploadFiles/" /> 

	<!-- 访问拦截  -->  
  	<mvc:interceptors>
		<mvc:interceptor>
			<mvc:mapping path="/**/**"/>
			<bean class="com.fh.interceptor.LoginHandlerInterceptor"/>
		</mvc:interceptor>
	</mvc:interceptors>
	 
	<!-- 配置SpringMVC的视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<!-- 异常处理 -->
	<bean id="exceptionResolver" class="com.fh.resolver.MyExceptionResolver"></bean>
	
	
	
	<!-- 上传拦截,如最大上传值及最小上传值 -->
	  <bean id="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >   
		  <property name="maxUploadSize">    
	          <value>104857600</value>    
	       </property>   
	        <property name="maxInMemorySize">    
	            <value>4096</value>    
	        </property>   
	         <property name="defaultEncoding">    
	            <value>utf-8</value>    
	        </property> 
    </bean>  
	
</beans>

 

 

 

 AppalicationContext.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:aop="http://www.springframework.org/schema/aop" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/aop 
						http://www.springframework.org/schema/aop/spring-aop-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/tx 
						http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	">
	
	<!-- 启用注解 -->
	<context:annotation-config />
	
	<!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
	<context:component-scan base-package="com.fh">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
    	<property name="dataSource" ref="dataSource"></property>
 	</bean>
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
		<property name="locations">  
			<list>  
                 <value>/WEB-INF/classes/dbconfig.properties</value>  
            </list>  
        </property>  
	</bean> 
	
	<!-- 阿里 druid数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">  
         <!-- 数据库基本信息配置 -->
         <property name="url" value="${url}" />  
         <property name="username" value="${username}" />  
         <property name="password" value="${password}" />  
         <property name="driverClassName" value="${driverClassName}" />  
         <property name="filters" value="${filters}" />  
   		 <!-- 最大并发连接数 -->
         <property name="maxActive" value="${maxActive}" />
         <!-- 初始化连接数量 -->
         <property name="initialSize" value="${initialSize}" />
         <!-- 配置获取连接等待超时的时间 -->
         <property name="maxWait" value="${maxWait}" />
         <!-- 最小空闲连接数 -->
         <property name="minIdle" value="${minIdle}" />  
   		 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />  
         <property name="validationQuery" value="${validationQuery}" />  
         <property name="testWhileIdle" value="${testWhileIdle}" />  
         <property name="testOnBorrow" value="${testOnBorrow}" />  
         <property name="testOnReturn" value="${testOnReturn}" />  
         <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
         <!-- 打开removeAbandoned功能 -->
         <property name="removeAbandoned" value="${removeAbandoned}" />
         <!-- 1800秒,也就是30分钟 -->
         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
         <!-- 关闭abanded连接时输出错误日志 -->   
         <property name="logAbandoned" value="${logAbandoned}" />
	</bean>  
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception"/>
			<tx:method name="insert*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" read-only="false" 
			           rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>
	
	<aop:aspectj-autoproxy proxy-target-class="true"/>
	
	<!-- 事物处理 -->
	<aop:config>
		<aop:pointcut id="pc" expression="execution(* com.fh.service..*(..))" />
		<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
	</aop:config>
	
	<!-- 配置mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- mapper扫描 -->
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
    </bean>
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>
	
	<!-- ================ Shiro start ================ -->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="ShiroRealm" />
		</bean>
		
		<!-- 項目自定义的Realm -->
	    <bean id="ShiroRealm" class="com.fh.interceptor.shiro.ShiroRealm" ></bean>
		
		<!-- Shiro Filter -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<property name="securityManager" ref="securityManager" />
			
			<property name="loginUrl" value="/" />
			
			<property name="successUrl" value="/main/index" />
			
			<property name="unauthorizedUrl" value="/login_toLogin" />
			
			<property name="filterChainDefinitions">
				<value>
				/static/login/** 	= anon
				/static/js/myjs/** 	= authc
				/static/js/** 		= anon
	           	/code.do 			= anon
	           	/login_login	 	= anon
	           	/app**/** 			= anon
	           	/weixin/** 			= anon
	           	/**					= authc
				</value>
			</property>
		</bean>
	<!-- ================ Shiro end ================ -->
	
   
</beans>

 

===========================

Ehcache 缓存

合理使用缓存

在**mapper.xml 文件如同加入

<!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->  

 <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>  

<!-- <cache type="org.mybatis.caches.ehcache.EhcacheCache"/> -->  

 

这样本页面所有都默认加入缓存,请注意不能乱加,具体如何合理加入缓存,请百度搜索详细资料,我就不在此啰嗦

单个开关

Insert  update  delete   flushCache="false"

Select  useCache="false"

 
 

=================================================

=======================

项目用到spring+mybatis框架,弄了一上午的spring+ehcache的整合,就是不见效果,后来发现Mybatis与Ehcache整合也需要进行配置,两个都配置会大大降低数据库压力。下面把我的配置过程写下来供大家参考。

 

1. 下载mybatis相关包与ehcache相关包

下载地址为:https://github.com/mybatis/ehcache-cache/releases

2. 在Map文件中打开echached效果,userMapper.xml文件内容如下:

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.erpbase.dao.UserMapper">  
  4.               <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->  
  5.     <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />  
  6.     <cache type="org.mybatis.caches.ehcache.EhcacheCache" />  
  7.     ......  
  8. </mapper>  

 3. 配置ehcache.xml 

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  
  3.     <diskStore path="java.io.tmpdir"/>   
  4.      
  5.     <defaultCache      
  6.             maxElementsInMemory="3000"      
  7.             eternal="false"      
  8.             timeToIdleSeconds="3600"      
  9.             timeToLiveSeconds="3600"      
  10.             overflowToDisk="true"      
  11.             diskPersistent="false"      
  12.             diskExpiryThreadIntervalSeconds="100"      
  13.             memoryStoreEvictionPolicy="LRU"      
  14.             />      
  15.     <cache name="userCache"      
  16.            maxElementsInMemory="3000"      
  17.            eternal="false"      
  18.            overflowToDisk="true"      
  19.            timeToIdleSeconds="3600"      
  20.            timeToLiveSeconds="3600"      
  21.            memoryStoreEvictionPolicy="LFU"      
  22.             />    
  23.     ......  
  24. </ehcache>  

 参数说明:

 

 <!-- 

        name: cache的名字,用来识别不同的cache,必须惟一。   

maxElementsInMemory: 内存管理的缓存元素数量最大限值。   

maxElementsOnDisk: 硬盘管理的缓存元素数量最大限值。默认值为0,就是没有限制。   

eternal: 设定元素是否持久话。若设为true,则缓存元素不会过期。   

overflowToDisk: 设定是否在内存填满的时候把数据转到磁盘上。

timeToIdleSeconds: 设定元素在过期前空闲状态的时间,只对非持久性缓存对象有效。默认值为0,值为0意味着元素可以闲置至无限长时间。   

timeToLiveSeconds: 设定元素从创建到过期的时间。其他与timeToIdleSeconds类似。   

diskPersistent: 设定在虚拟机重启时是否进行磁盘存储,默认为false.(我的直觉,对于安全小型应用,宜设为true)。   

diskExpiryThreadIntervalSeconds: 访问磁盘线程活动时间。   

diskSpoolBufferSizeMB: 存入磁盘时的缓冲区大小,默认30MB,每个缓存都有自己的缓冲区。   

memoryStoreEvictionPolicy: 元素逐出缓存规则。共有三种,Recently Used (LRU)最近最少使用,为默认。 First In First Out (FIFO),先进先出。Less Frequently Used(specified as LFU)最少使用  

--> 

4. 配置applicationContext-ehcache.xml

 

Java代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!-- /** * * 缓存配置 *  * */ -->  
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"  
  6.     xsi:schemaLocation="      
  7.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  8.     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring    
  9.     http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">  
  10.   
  11.     <!-- <ehcache:annotation-driven /> -->  
  12.   
  13.     <ehcache:annotation-driven cache-manager="ehcacheManager" />  
  14.   
  15.     <ehcache:config cache-manager="ehcacheManager">  
  16.         <ehcache:evict-expired-elements interval="60" />  
  17.     </ehcache:config>  
  18.       
  19.     <bean id="ehcacheManager"  
  20.         class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  21.         <property name="configLocation" value="classpath:ehcache.xml" />  
  22.     </bean>  
  23. </beans>  

 5. 在spring-mvc.xml 中加入如下内容,将ehcache相关配置装配到spring容器中:

 

 

Java代码   收藏代码
  1. <!-- 加载ehcache缓存配置文件     
  2.         说明:在这里我遇到了这样一个问题,当使用@Service等注解的方式将类声明到配置文件中时,    
  3.         就需要将缓存配置import到主配置文件中,否则缓存会不起作用    
  4.         如果是通过<bean>声明到配置文件中时,    
  5.         则只需要在web.xml的contextConfigLocation中加入applicationContext-ehcache.xml即可,    
  6.         不过还是推荐使用如下方式吧,因为这样不会有任何问题    
  7.     -->    
  8.     <import resource="classpath:applicationContext-ehcache.xml"/>  

 6. 在userServiceImpl.java中加入通过注解进行配置:

 

 

Java代码   收藏代码
  1.        @Cacheable(cacheName="userCache")  <strong>//这里的cacheName要跟ehcache.xml中保持一致</strong>  
  2. public List<User> getUserList(User user, Map<String, Object> map) {  
  3.     long l1 = new Date().getTime();  
  4.   
  5.     List<User> list = userMapper.getUserList(user);  
  6.     Integer listSize = userMapper.getUserCount(user);  
  7.   
  8.     long l2 = new Date().getTime();  
  9.     System.out.println("++++++++++++total time use: " + (l2-l1));  
  10.   
  11.     map.put("rows", list);  
  12.     map.put("total", listSize);  
  13.   
  14.     return list;  
  15. }  

 

 

到此spring+mybatis+EHCache配置完成。可以对比在加上@Cacheable(cacheName="userCache")和不加的两种情况下的(l2-l1)的时间,在我本地如果不加用时在40ms左右,加上之后第一次加载是40ms,第二次用时1ms,说明第一次加载的数据已经被放到缓存当中去,可见效率得到极大提升。

 

 

 

拓展说明:

对于清除缓存的方法,ehcache提供了两种,一种是在ehcache.xml中配置的时间过后自动清除,一种是在数据发生变化后触发清除。个人感觉第二种比较好。可以将 

@TriggersRemove(cacheName="userCache",removeAll=true)

@TriggersRemove(cacheName="userCache", when=When.AFTER_METHOD_INVOCATION, removeAll=true) 

这句代码加到service里面的添加、删除、修改方法上。这样只要这几个方法有调用,缓存自动清除。

 

对于Mybatis更简单,对不想缓存的sql结果,可以再后面添加useCache="false"即可:

 

Java代码   收藏代码
  1. <select id="getLabelValueList" resultMap="BaseResultMap" parameterType="com.Product" useCache="false">  
  2. select Id, Name  
  3. from Product  
  4. where Enable = 1  
  5. <if test="shopid != null and shopid != 0 " >  
  6.   AND Id not in (select Productid from shopproduct where shopid = #{shopid})   
  7. </if>  
  8. order by Id  
  9. </select>  

==============================================

使用Maven搭建Spring+SpringMVC+Mybatis+ehcache项目

==============================================

搭建Spring不用说肯定是必须的,前端使用SpringMVC 而不使用Struts2是因为SpringMVC的效率要比struts2要高很多,虽然struts2有丰富的标签可以使用,使用Mybatis是因为以后项目要做报表模块,Mybatis使用SQL Mapping的方式很容易操作数据库。

这里我们使用intellij idea来做我们的开发工具,废话不多说,开干。框架的版本是

Spring 3.2.8.RELEASE

Spring MVC 3.2.8.RELEASE

mybatis 3.2.8

一、创建Maven Web项目

(略)本项目中用的maven是 3.3.3版本的,要求jdk版本是1.7之后的

二、在pom.xml中加入项目依赖的jar包

项目包依赖关系如下:

pom文件如下:

<properties><!-- Generic properties --><java.version>1.7</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><!-- Web --><jsp.version>2.2</jsp.version><jstl.version>1.2</jstl.version><servlet.version>3.0.1</servlet.version><!-- Spring --><spring-framework.version>3.2.8.RELEASE</spring-framework.version><!-- Logging --><slf4j.version>1.7.5</slf4j.version><!-- Test --><junit.version>4.11</junit.version></properties><dependencies><!--Aspect oriented--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.8.7</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency><!-- Spring MVC --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring-framework.version}</version></dependency><!-- Spring and Transactions --><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring-framework.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring-framework.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring-framework.version}</version><scope>test</scope></dependency><!-- Spring and Transactions --><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring-framework.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring-framework.version}</version></dependency><!-- Logging with SLF4J & Log4j --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version><scope>compile</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.12</version></dependency><!-- mybatis &mysql --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.8</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-ehcache</artifactId><version>1.0.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><!--commons--><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.5</version></dependency><!-- Other Web dependencies --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${servlet.version}</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>${jsp.version}</version><scope>provided</scope></dependency><dependency><groupId>org.apache.taglibs</groupId><artifactId>taglibs-standard-impl</artifactId><version>1.2.3</version></dependency></dependencies>

三、添加日志的支持

日志我们使用slf4j,并用log4j来实现

SLF4J不同于其他日志类库,与其它有很大的不同。SLF4J(Simple logging Facade for Java)不是一个真正的日志实现,而是一个抽象层( abstraction layer),它允许你在后台使用任意一个日志类库。

SLF4J还有很多优点,具体可以参考 http://javarevisited.blogspot.com/2013/08/why-use-sl4j-over-log4j-for-logging-in.html

日志的实现类还是用熟悉的log4j,先要在项目的pom.xml文件中加入日志的支持

		<!-- Logging with SLF4J & Log4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.5</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.12</version>
		</dependency>

配置很简单,log4j的详细配置可以参考log4j官网

log4j.properties

log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Threshold = DEBUG
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d %p [%c]  - %m%n


log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.File=${catalina.home}/logs/
log4j.appender.A2.Append=false
log4j.appender.A2.DatePattern='-'yyyy-MM-dd'.log'
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d %p [%c] - %m%n

三、整合Spring+Mybatis

把Spring和Mybatis的jar包都引入之后就可以整合这两个框架了

先看下项目的相关配置文件

其中gererator.properties和generatorConfig.xml是用来根据数据库自动生成mapper接口,实体,以及映射文件的

mybatis-config是mybatis的一些映射的相关配置,比如mapper,cache等

spring-mybatis是自动扫描,自动装配mapper以及datasource,sqlSessionFactory等配置

这些会在接下来详细说明

1.JDBC配置文件

jdbc.initialSize=5
jdbc.maxActive=20
jdbc.maxIdle=5
jdbc.defaultAutoCommit=true
jdbc.removeAbandoned=true  
jdbc.removeAbandonedTimeout=30 
jdbc.logAbandoned=true
jdbc.testWhileIdle=true
jdbc.validationQuery=select 1 from dual
jdbc.timeBetweenEvictionRunsMillis=30000
jdbc.numTestsPerEvictionRun=10
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

2.创建spring-mybatis.xml

创建spring-mybatis.xml来配置mybatis的一些信息,主要是数据源、事务、自动扫描、自动注入等功能

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"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/aop http://www.springframework.org/schema/aop/spring-aop-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/context	http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- enable component scanning --><context:component-scanbase-package="com.zeusjava"/><!-- enable autowire --><context:annotation-config/><!-- enable transaction demarcation with annotations --><tx:annotation-driven/><!-- 读取mysql jdbc的配置--><beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="location"value="classpath:jdbc.properties"/></bean><!-- 配置数据源,从上面配置文件读取--><!-- 数据源 --><beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"><propertyname="driverClassName"value="${jdbc.driverClassName}"/><propertyname="url"value="${jdbc.url}"/><propertyname="username"value="${jdbc.username}"/><propertyname="password"value="${jdbc.password}"/><propertyname="initialSize"value="${jdbc.initialSize}"/><propertyname="maxActive"value="${jdbc.maxActive}"/><propertyname="maxIdle"value="${jdbc.maxIdle}"/><propertyname="defaultAutoCommit"value="${jdbc.defaultAutoCommit}"/><propertyname="removeAbandoned"value="true"/><propertyname="removeAbandonedTimeout"value="${jdbc.removeAbandonedTimeout}"/><propertyname="logAbandoned"value="${jdbc.logAbandoned}"/><!--主动检测连接池是否有效--><propertyname="testWhileIdle"value="${jdbc.testWhileIdle}"/><propertyname="validationQuery"value="${jdbc.validationQuery}"/><propertyname="timeBetweenEvictionRunsMillis"value="${jdbc.timeBetweenEvictionRunsMillis}"/><propertyname="numTestsPerEvictionRun"value="${jdbc.numTestsPerEvictionRun}"/></bean><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><!-- 配置扫描Domain的包路径 --><propertyname="typeAliasesPackage"value="com.zeusjava.kernel.entity"/><!-- 配置mybatis配置文件的位置 --><propertyname="configLocation"value="classpath:mybatis-config.xml"/><!-- 配置扫描Mapper XML的位置 --><propertyname="mapperLocations"value="classpath*:com/zeusjava/kernel/mapper/*.xml"/></bean><!-- 配置扫描Mapper接口的包路径 --><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="basePackage"value="com.zeusjava.kernel.dao"/></bean><beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate"><constructor-argref="sqlSessionFactory"/></bean><beanid="mybatisTransactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"p:dataSource-ref="dataSource"/><tx:adviceid="txAdvice"transaction-manager="mybatisTransactionManager"><tx:attributes><tx:methodname="save*"propagation="REQUIRED"/><tx:methodname="insert*"propagation="REQUIRED"/><tx:methodname="add*"propagation="REQUIRED"/><tx:methodname="update*"propagation="REQUIRED"/><tx:methodname="delete*"propagation="REQUIRED"/><tx:methodname="remove*"propagation="REQUIRED"/><tx:methodname="accept*"propagation="REQUIRED"/><tx:methodname="reject*"propagation="REQUIRED"/><tx:methodname="execute*"propagation="REQUIRED"/><tx:methodname="del*"propagation="REQUIRED"/><tx:methodname="recover*"propagation="REQUIRED"/><tx:methodname="sync*"propagation="REQUIRED"/><tx:methodname="*"read-only="true"/></tx:attributes></tx:advice><aop:config><aop:pointcutid="txPointcut"expression="execution(public * com.zeusjava.kernel.service.*.*(..))"/><aop:advisorpointcut-ref="txPointcut"advice-ref="txAdvice"/></aop:config></beans>

3.创建数据库表

  CREATE TABLE `user` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `user_name` varchar(40) NOT NULL,  
  `password` varchar(255) NOT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  


insert  into `user`(`id`,`user_name`,`password`) values (1,'赵宏轩','123456');  

4.创建User的Mapping映射文件,User实体和Mapper接口

1.在pom.xml中添加mybatis-generator-maven-plugin插件

<build><finalName>HelloSSM</finalName><plugins><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.2</version><configuration><verbose>true</verbose><overwrite>true</overwrite></configuration></plugin></plugins></build>
``
`
####2.在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件以及和generator有关的属性文件,作为mybatis-generator-maven-plugin 插件的执行目标
![目录结构](http://i13.tietuku.com/274205a36b4c55d5.png)
 generatorConfig.xml
 ```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><!--导入属性配置 --><propertiesresource="generator.properties"></properties><!--指定特定数据库的jdbc驱动jar包的位置 --><classPathEntrylocation="${jdbc.driverLocation}"/><contextid="default"targetRuntime="MyBatis3"><!-- optional,旨在创建class时,对注释进行控制 --><commentGenerator><propertyname="suppressDate"value="true"/></commentGenerator><!--jdbc的数据库连接 --><jdbcConnectiondriverClass="${jdbc.driverClassName}"connectionURL="${jdbc.url}"userId="${jdbc.username}"password="${jdbc.password}"></jdbcConnection><javaTypeResolver><propertyname="forceBigDecimals"value="false"/></javaTypeResolver><javaModelGeneratortargetPackage="com.zeusjava.kernel.entity"targetProject="src/main/java"><!-- 是否对model添加 构造函数 --><propertyname="constructorBased"value="true"/><!-- 是否允许子包,即targetPackage.schemaName.tableName --><propertyname="enableSubPackages"value="false"/><!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 --><propertyname="immutable"value="true"/><propertyname="trimStrings"value="true"/></javaModelGenerator><!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 --><sqlMapGeneratortargetPackage="com.zeusjava.kernel.mapper"targetProject="src/main/java"><propertyname="enableSubPackages"value="false"/></sqlMapGenerator><javaClientGeneratortargetPackage="com.zeusjava.kernel.dao"targetProject="src/main/java"type="MIXEDMAPPER"><propertyname="enableSubPackages"value=""/><propertyname="exampleMethodVisibility"value=""/><propertyname="methodNameCalculator"value=""/><propertyname="rootInterface"value=""/></javaClientGenerator><tabletableName="user"domainObjectName="User"enableCountByExample="false"enableUpdateByExample="false"enableDeleteByExample="false"enableSelectByExample="false"selectByExampleQueryId="false"></table></context></generatorConfiguration>

还有与之相关联的generator.properties文件

jdbc.driverLocation=D:\\idea\\maven\\mysql\\mysql-connector-java\\5.1.29\\mysql-connector-java-5.1.29.jar
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

3.在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件

1).点击Run,选择Edit Configurations

2).点击左上角的  + ,选择  maven 
3).输入name,选择Working directory,Command line 填上  mybatis-generator:generate -e 

4.点击运行查看结果

运行插件控制台如果打印build Success 就说明成功了

会在指定目录产生三个文件,分别是  实体 ,  Mapper接口 ,  Mapping配置文件 

5.创建mybatis-config.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration	 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"	 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<settingname="cacheEnabled"value="false"/>
		<settingname="lazyLoadingEnabled"value="true"/>
		<settingname="aggressiveLazyLoading"value="false"/>
		<settingname="localCacheScope"value="STATEMENT"/>
		<settingname="multipleResultSetsEnabled"value="true"/>
		<settingname="useColumnLabel"value="true"/>
		<settingname="defaultStatementTimeout"value="25000"/>
		<settingname="mapUnderscoreToCamelCase"value="true"/>
		<!-- 是否使用插入数据后自增主键的值,需要配合keyProperty使用 -->
		<settingname="useGeneratedKeys"value="true"/>
	</settings>
	<typeAliases>
		<typeAliasalias="User"type="com.zeusjava.kernel.entity.User"/>
	</typeAliases>
	<mappers>
		<!--<mapper resource="com/zeusjava/kernel/mapper/UserMapper.xml"/>-->
		<!--<mapper class="com.zeusjava.kernel.dao.UserMapper"/>-->
		<!--<mapper url="file:///D:/idea/HelloSSM/src/main/java/com/zeusjava/kernel/mapper/UserMapper.xml"/>-->
		<packagename="com.zeusjava.kernel.dao"/>
		<!--<mapper class="com.zeusjava.kernel.dao.UserMapper"/>-->
	</mappers>
</configuration>

其中最后的mapper有四种配置方式,但是,在我的电脑上只有使用url的方式才行,不知道是怎么回事,待查询。

6.建立Service接口和实现类

IUserService.java代码如下

package com.zeusjava.kernel.service;

import com.zeusjava.kernel.entity.User;

/** * Created by LittleXuan on 2015/10/17. */
public interfaceIUserService{
    publicUsergetUserById(intuserId);
}

UserServiceImpl.java的代码如下

package com.zeusjava.kernel.service.impl;
import com.zeusjava.kernel.dao.UserMapper;
import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/** * Created by LittleXuan on 2015/10/17. */
@Service("userService")
public class IUserServiceImpl implements IUserService {
	@Resource
	private UserMapper userMapper;
	@Override
	public User getUserById(int userId) {
		return this.userMapper.selectByPrimaryKey(userId);
	}
}

7.建立测试类

import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/** * Created by LittleXuan on 2015/10/17. */
@RunWith(SpringJUnit4ClassRunner.class)	 //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:conf/spring/beans-mybatis.xml"})
public classSSMTest{
	private static Logger logger = LoggerFactory.getLogger(SSMTest.class);
	@Resource
	private IUserService userService = null;
	@Test
	public void test1() {
		User user = userService.getUserById(1);
		logger.info("姓名:"+user.getUserName());
	}
}

运行单元测试,结果如下,说明spring和mybatis的整合已经完成。

四、和SpringMVC整合

和Spring MVC的整合就简单的多了,只需要添加一个Spring MVC配置文件,和配置一下Web.xml就行了,我在前面的博客写过一篇文章,请戳 Maven整合Spring MVC搭建笔记-ZeusJava Blog

1.配置Spring MVC 配置文件zeusjava-servlet.xml

在配置文件里主要配置 自动扫描控制器 , 视图解析器 , 注解

<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"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  ">
	<!-- 激活利用注解进行装配 -->
	<context:annotation-config/>
	<!-- ① :对 web 包中的所有类进行扫描,以完成 Bean 创建和自动依赖注入的功能 -->
	<context:component-scanbase-package="com.zeusjava.web.controller"/>
	<!-- ② :启动 Spring MVC 的注解功能,完成请求和注解 POJO 的映射 --> 
	<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
	<!--  ③ :对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/WEB-INF/jsp/"p:suffix=".jsp"/>
</beans>

2.配置web.xml

在web.xml里配置Spring MVC的DispatcherServlet和mybatis的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0">
	<display-name>HelloSSM</display-name>
	<!-- Spring和mybatis的配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mybatis.xml</param-value>
	</context-param>
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<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>
	<!-- Spring监听器 -->
	<listener>
		<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>
		<servlet-name>SpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>  

3.在WEB_INF/jsp建立一个简单的测试页面user.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<html><body><h1>用户ID为${user.id}的用户详情</h1>
ID:${user.id}
姓名:${user.userName}</body></html>

4.建立User控制器

通过url传入一个id,解析这个id然后查询数据库,得到User对象放入jsp页面显示。

package com.zeusjava.web.controller;
/** * Created by LittleXuan on 2015/10/18. */
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/user")
public classUserController{
	@Resource
	private IUserService userService;
	@RequestMapping(value="/userInfo/{id}",method=RequestMethod.GET)
	public String toIndex(HttpServletRequest request, Model model,@PathVariable("id") String id) {
		if(StringUtils.isEmpty(id)){
			throw new IllegalArgumentException("id不能为空");
		}
		int userId = Integer.parseInt(id);
		User user = this.userService.getUserById(userId);
		model.addAttribute("user", user);
		return "user";
	}
}

5.添加tomcat服务器并部署war包

1. File-Project Structure 点击 Artifacts 一栏

点击 + ,选择 Web-Application-Exploded 然后选择from maven选中本项目

Web Application Exploded是没有压缩的war包,相当于文件夹

Web Application Achieved是雅俗后的war包

2.intellij会自动帮我们生成一个war包

3.点击 Run-Run Configurations

点击 + 选择 tomcat server->local 

4.点击 Configure

5.点击 Deployment选项卡 ,点击 + 号,选择一个artifact,就是第二部的war包

6.OK启动服务器

在任务栏输入 http://localhost:8081/HelloSSM/user/userInfo/1 ,回车,结果如下:

一个简单的SSM项目环境就搭建好了。

五、和ehcache的整合

Ehcache是Hibernate的默认的cache,但是mybatis中需要自己集成,在Mybatis中使用会大大增加性能,下面开始整合mybatis和Ehcache

1.使用首先要把需要的jar包依赖加入pom中

 <dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-ehcache</artifactId>
	<version>1.0.0</version>
 </dependency>
 <dependency>
	<groupId>org.ehcache</groupId>
	<artifactId>ehcache</artifactId>
	<version>3.0.0.m3</version>
 </dependency>

2.在Resource中添加一个ehcache.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"updateCheck="false">
       <diskStorepath="java.io.tmpdir"/>
       <defaultCacheeternal="false"maxElementsInMemory="1000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="0"timeToLiveSeconds="600"memoryStoreEvictionPolicy="LRU"/>
       <cachename="testCache"eternal="false"maxElementsInMemory="100"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="0"timeToLiveSeconds="300"memoryStoreEvictionPolicy="LRU"/>
</ehcache>

说明:

name:Cache的唯一标识  
maxElementsInMemory:内存中最大缓存对象数  
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大  
eternal:Element是否永久有效,一但设置了,timeout将不起作用  
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中  
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大  
timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大   
diskPersistent:是否缓存虚拟机重启期数据  
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒  
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区  
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)   

3.在spring-mybatis.xml中加入chache配置

    <!-- 使用ehcache缓存 -->
    <beanid="ehCacheManager"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <propertyname="configLocation"value="classpath:ehcache.xml"/>
    </bean>

4.在mapper.xml中配置cache

<cachetype="org.mybatis.caches.ehcache.LoggingEhcache">  
	<propertyname="timeToIdleSeconds"value="3600"/>
	<propertyname="timeToLiveSeconds"value="3600"/>
	<propertyname="maxEntriesLocalHeap"value="1000"/>  
	<propertyname="maxEntriesLocalDisk"value="10000000"/>  
	<propertyname="memoryStoreEvictionPolicy"value="LRU"/>  
</cache>

type是使用的cache类型, LoggingEhcache 会记录下日志,如果不需要日志的话可以使用 EhcacheCache 
这样配置之后,所以的操作都会执行缓存,如果有的操作不需要的话,可以在sql配置里将useCache设置为 false

    @Select({
	"select",
	"id, user_name, password",
	"from user",
	"where id = #{id,jdbcType=INTEGER}"
    })
    @Options(useCache = false,timeout = 10000,flushCache = false)
    @ResultMap("BaseResultMap")
    User selectByPrimaryKey(Integer id);

5.测试性能

测试代码

 @Test
	publicvoidtest1(){
		long beginTime=System.nanoTime();
		User user = userService.getUserById(1);
		long endTime=System.nanoTime();
		System.out.println("查询时间 :" + (endTime-beginTime)+"ns");
		logger.info("姓名:"+user.getUserName());
	}

第一次把useCache设置为 false

第二次把useCache设置为 true 

两次执行的时间差了大约 0.4 秒

整个项目已经放到github上了,有需要的可以前往 HelloSSM 查看, 不懂的地方欢迎探讨...

猜你喜欢

转载自4636.iteye.com/blog/2339840