Spring 整合 MyBatis 整合步骤
1、建立工程,加入Spring和MyBatis的有关jar包
2、建立开发目录结构,创建实体类
3、创建访问数据接口
4、数据数据访问接口的实现类
5、配置SQL映射语句文件
6、配置Mybatis应用配置文件
7、配置Spring应用配置文件
---------------------------------------------
配置
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文件内容如下:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.erpbase.dao.UserMapper">
- <!-- 以下两个<cache>标签二选一,第一个可以输出日志,第二个不输出日志 -->
- <cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
- <cache type="org.mybatis.caches.ehcache.EhcacheCache" />
- ......
- </mapper>
3. 配置ehcache.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache
- maxElementsInMemory="3000"
- eternal="false"
- timeToIdleSeconds="3600"
- timeToLiveSeconds="3600"
- overflowToDisk="true"
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds="100"
- memoryStoreEvictionPolicy="LRU"
- />
- <cache name="userCache"
- maxElementsInMemory="3000"
- eternal="false"
- overflowToDisk="true"
- timeToIdleSeconds="3600"
- timeToLiveSeconds="3600"
- memoryStoreEvictionPolicy="LFU"
- />
- ......
- </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
- <?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:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
- http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">
- <!-- <ehcache:annotation-driven /> -->
- <ehcache:annotation-driven cache-manager="ehcacheManager" />
- <ehcache:config cache-manager="ehcacheManager">
- <ehcache:evict-expired-elements interval="60" />
- </ehcache:config>
- <bean id="ehcacheManager"
- class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
- <property name="configLocation" value="classpath:ehcache.xml" />
- </bean>
- </beans>
5. 在spring-mvc.xml 中加入如下内容,将ehcache相关配置装配到spring容器中:
- <!-- 加载ehcache缓存配置文件
- 说明:在这里我遇到了这样一个问题,当使用@Service等注解的方式将类声明到配置文件中时,
- 就需要将缓存配置import到主配置文件中,否则缓存会不起作用
- 如果是通过<bean>声明到配置文件中时,
- 则只需要在web.xml的contextConfigLocation中加入applicationContext-ehcache.xml即可,
- 不过还是推荐使用如下方式吧,因为这样不会有任何问题
- -->
- <import resource="classpath:applicationContext-ehcache.xml"/>
6. 在userServiceImpl.java中加入通过注解进行配置:
- @Cacheable(cacheName="userCache") <strong>//这里的cacheName要跟ehcache.xml中保持一致</strong>
- public List<User> getUserList(User user, Map<String, Object> map) {
- long l1 = new Date().getTime();
- List<User> list = userMapper.getUserList(user);
- Integer listSize = userMapper.getUserCount(user);
- long l2 = new Date().getTime();
- System.out.println("++++++++++++total time use: " + (l2-l1));
- map.put("rows", list);
- map.put("total", listSize);
- return list;
- }
到此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