Spring+Mybatis+ehcache整合

来源:互联网 发布:手机淘宝底部导航设置 编辑:程序博客网 时间:2024/05/22 06:44

1.先贴一张项目结构图和引入的jar包

这里写图片描述

这里写图片描述

这里写图片描述
有些jar包其实是不必要的,可以先加入spring,mybatis,ehcache的jar包,然后根据报错逐步加入需要的jar包。


2.先向项目中加入Mybatis

(1)在根目录下创建mybatis-config.xml

(2)mybatis-config.xml中settings属性的设置可以在Mybatis官网文档中找到:
这里写图片描述

(3)mybatis-config.xml中添加数据库的连接信息,在Mybatis官网文档中也可以找到相关的说明:
这里写图片描述
数据库的连接在整合Spring之后,交给Spring来处理,这里给出,只是想告诉大家,什么事情原本是Mybatis做的,但是整合Spring之后,就交由Spring来做了。

(4)Mybatis需要手动编写操作数据库的sql,在mybatis-config.xml中需要引入这些xml文件,这部分,实际编码的时候再给出。


3.向项目中加入Ehcache

(1)创建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"><defaultCache      maxElementsInMemory="10000"       eternal="false"       timeToIdleSeconds="3600"       timeToLiveSeconds="3600"       overflowToDisk="true"       diskPersistent="false"       diskExpiryThreadIntervalSeconds="100"       memoryStoreEvictionPolicy="LRU" />  <cache name="studentCache"       maxElementsInMemory="3000"       eternal="false"       overflowToDisk="true"      diskPersistent="false"       timeToIdleSeconds="360000"       timeToLiveSeconds="360000"       memoryStoreEvictionPolicy="LFU" /> </ehcache>

这里定义了一个名称为studentCache的缓存,接下来会使用这个缓存。


4.向项目中加入Spring,整合Mybatis和Ehcache

(1)在根路径创建application-context.xml文件。

(2)在application-context.xml中加入数据库的连接信息:

<bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">       <property name="driverClassName">           <value>com.mysql.jdbc.Driver</value>       </property>       <property name="url">          <value>jdbc:mysql://127.0.0.1:3306/xxx</value>       </property>       <property name="username">          <value>xxx</value>       </property>       <property name="password">          <value>xxx</value>       </property>  </bean>  

(3)由Spring创建Mybatis的SqlSessionFactory

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">         <property name="dataSource" ref="jdbcDataSource" />         <property name="configLocation" value="classpath:mybatis-config.xml"></property>     </bean>  

(4)向application-context.xml中注册ehcache

<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">     <property name="configLocation" value="classpath:ehcache.xml"></property></bean><bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">    <property name="cacheManager" ref="ehCacheManager"></property>    <property name="transactionAware" value="true"></property></bean><cache:annotation-driven cache-manager="cacheManager" />

(5)添加包注解的扫描

<context:component-scan base-package="gdut.ff.bean"></context:component-scan>

5.编码测试Spring整合Ehcache的效果

(1)使用Mybatis的Mapper接口形式操作数据库

a.定义StudentDao接口

public interface StudentDao {    @Cacheable("studentCache")    public Map<String,Object> selectStudentById(int id);    @CacheEvict("studentCache")    public Map<String,Object> getStudentById(int id);}

@Cacheable(“studentCache”):第一次请求没有命中缓存,会去数据库中查询,将查询的结果放入这个名称的缓存中,接下来在缓存有效的时间内,请求会去缓存中获取数据。
@CacheEvict(“studentCache”):清除名称为studentCache的缓存。

b.对应的sql:我创建了一个StudentMapper.xml。
需要在mybatis-config.xml中引入这个xml。

<mappers>    <mapper resource="gdut/ff/bean/StudentMapper.xml"/></mappers>

对应的statement:
这里写图片描述

在application-context.xml中注册这个StudentDao
这里写图片描述

c.测试

@Testpublic void testSelectStudent(){    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");    StudentDao studentDao = (StudentDao) context.getBean("studentDao");    Map<String,Object> map1 = studentDao.selectStudentById(1);    System.out.println(map1.get("STU_NAME"));    Map<String,Object> map3 = studentDao.selectStudentById(1);    System.out.println(map3.get("STU_NAME"));    Map<String,Object> map2 = studentDao.getStudentById(1);    System.out.println(map2.get("STU_NAME"));}

d.测试结果
这里写图片描述
相当于mybatis的二级缓存

(2)使用Mybatis自带的API(命名空间+id)操作数据库
a.创建一个StudentService

@Servicepublic class StudentService {    @Autowired    private SqlSessionFactory sqlSessionFactory;    @Cacheable("studentCache")    public Map<String,Object> selectStudentById(int id){        SqlSession session = sqlSessionFactory.openSession();        Map<String,Object> map = new HashMap<String,Object>();        map.put("id",id);        return session.selectOne("gdut.ff.bean.StudentDao.selectStudentById",map);    }}

注意:这里使用的是注解的形式向Spring中注册StudentService,session.selectOne()调用的是(1)b中的语句。

b.测试

@Testpublic void testGetStudent(){    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");    StudentService studentService = (StudentService) context.getBean("studentService");    Map<String,Object> map1 = studentService.selectStudentById(1);    System.out.println(map1.get("STU_NAME"));    Map<String,Object> map2 = studentService.selectStudentById(1);    System.out.println(map2.get("STU_NAME"));}

c.运行结果
这里写图片描述