mybatis+spring+c3p0+maven+ehcache
項目截圖
?
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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.alibaba</groupId><artifactId>mybatispring</artifactId><version>0.0.1-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><springversion>4.0.0.RELEASE</springversion><junitversion>4.12</junitversion></properties><dependencies><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junitversion}</version><scope>test</scope></dependency><!-- db --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.35</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.2.2</version></dependency><!-- spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>${springversion}</version><type>jar</type><scope>compile</scope></dependency><!-- cglib --><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>2.2.2</version></dependency><!-- log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- c3p0數(shù)據(jù)源 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5-pre10</version></dependency></dependencies></project>然后配置spring,applicationContext.xml
<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"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "><!-- 加載配置文件 --><context:property-placeholder location="classpath:db.properties" /><!-- 數(shù)據(jù)源,使用dbcp --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><property name="driverClass" value="${jdbc.driverClass}" /><property name="jdbcUrl" value="${jdbc.jdbcUrl}" /><property name="user" value="${jdbc.user}" /><property name="password" value="${jdbc.password}" /><property name="minPoolSize" value="${jdbc.miniPoolSize}" /><property name="maxPoolSize" value="${jdbc.maxPoolSize}" /><property name="initialPoolSize" value="${jdbc.initialPoolSize}" /><property name="maxIdleTime" value="${jdbc.maxIdleTime}" /><property name="acquireIncrement" value="${jdbc.acquireIncrement}" /><property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" /><property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}" /><property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" /><property name="automaticTestTable" value="${jdbc.automaticTestTable}" /><property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" /><property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" /></bean><!-- sqlSessinFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 加載mybatis的配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /><!-- 數(shù)據(jù)源 --><property name="dataSource" ref="dataSource" /></bean><!-- 原始dao接口 --><bean id="userDao" class="com.alibaba.dao.UserDaoImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean><!-- mapper配置 MapperFactoryBean:根據(jù)mapper接口生成代理對象 --><!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> mapperInterface指定mapper接口 <property name="mapperInterface" value="cn.itcast.ssm.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> --><!-- mapper批量掃描,從mapper包中掃描出mapper接口,自動創(chuàng)建代理對象并且在spring容器中注冊 遵循規(guī)范:將mapper.java和mapper.xml映射文件名稱保持一致,且在一個目錄 中 自動掃描出來的mapper的bean的id為mapper類名(首字母小寫) --><!-- 指定掃描的包名 如果掃描多個包,每個包中間使用半角逗號分隔 --><!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.itcast.ssm.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> --></beans>引用的db.properties如下
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl = jdbc:mysql://localhost:3306/test jdbc.user = root jdbc.password = 123456 jdbc.miniPoolSize = 1 jdbc.maxPoolSize = 20 jdbc.initialPoolSize = 1 jdbc.maxIdleTime = 25000 jdbc.acquireIncrement = 1jdbc.acquireRetryAttempts = 30 jdbc.acquireRetryDelay = 1000 jdbc.testConnectionOnCheckin = true jdbc.automaticTestTable = c3p0TestTable jdbc.idleConnectionTestPeriod = 18000 jdbc.checkoutTimeout=3000SqlMapConfig.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><!-- 別名定義 --><typeAliases><!-- 批量別名定義 指定包名,mybatis自動掃描包中的po類,自動定義別名,別名就是類名(首字母大寫或小寫都可以)--><package name="com.alibaba"/></typeAliases><!-- 加載 映射文件 --><mappers><mapper resource="mybatis/UserMapper.xml"/><!-- 批量加載mapper指定mapper接口的包名,mybatis自動掃描包下邊所有mapper接口進(jìn)行加載遵循一些規(guī)范:需要將mapper接口類名和mapper.xml映射文件名稱保持一致,且在一個目錄 中上邊規(guī)范的前提是:使用的是mapper代理方法和spring整合后,使用mapper掃描器,這里不需要配置了--><!-- <package name="cn.itcast.ssm.mapper"/> --></mappers></configuration>UserDao.java
package com.alibaba.dao;import com.alibaba.po.User;public interface UserDao {public User findUserById(int id) throws Exception; }UserDaoImpl.java
package com.alibaba.dao;import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.support.SqlSessionDaoSupport;import com.alibaba.po.User;public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{public User findUserById(int id) throws Exception {SqlSession sqlSession = this.getSqlSession();User user = sqlSession.selectOne("mapper.UserMapper.getUser", id);return user;}}UserDaoTest.java
package com.alibaba.dao;import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.alibaba.po.User;public class UserDaoTest {private ApplicationContext applicationContext;//在setUp這個方法得到spring容器 @Beforepublic void setUp() throws Exception {applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic void testFindUserById() throws Exception {UserDao userDao = (UserDao) applicationContext.getBean("userDao");//調(diào)用userDao的方法User user = userDao.findUserById(1);System.out.println(user);}}?log4j如下
# Global logging configuration #\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n如果項目運(yùn)行會報c3p0找不到文件錯誤,那個沒影響,只需要把Log4jdebug改為Info即可,生產(chǎn)環(huán)境就不會報錯。
?
加入ehcache
<!-- ehcache --><dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>1.0.3</version></dependency><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache-core</artifactId><version>2.6.11</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.12</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.12</version></dependency><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>2.2.2</version></dependency>配置文件ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"><diskStore path="D:\develop\ehcache" /><defaultCache maxElementsInMemory="1000" maxElementsOnDisk="10000000"eternal="false" overflowToDisk="false" timeToIdleSeconds="120"timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120"memoryStoreEvictionPolicy="LRU"></defaultCache> </ehcache><!-- name:緩存名稱。
maxElementsInMemory:緩存最大個數(shù)。
eternal:對象是否永久有效,一但設(shè)置了,timeout將不起作用。
timeToIdleSeconds:設(shè)置對象在失效前的允許閑置時間(單位:秒)。僅當(dāng)eternal=false對象不是永久有效時使用,可選屬性,默認(rèn)值是0,也就是可閑置時間無窮大。
timeToLiveSeconds:設(shè)置對象在失效前允許存活時間,最大時間介于創(chuàng)建時間和失效時間之間。僅當(dāng)eternal=false對象不是永久有效時使用,默認(rèn)是0.,也就是對象存活時 間無窮大。
overflowToDisk:當(dāng)內(nèi)存中對象數(shù)量達(dá)到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
diskSpoolBufferSizeMB:這個參數(shù)設(shè)置DiskStore(磁盤緩存)的緩存區(qū)大小。默認(rèn)是30MB。每個Cache都應(yīng)該有自己的一個緩沖區(qū)。
maxElementsOnDisk:硬盤最大緩存?zhèn)€數(shù)。
diskPersistent:是否緩存虛擬機(jī)重啟期數(shù)據(jù) Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盤失效線程運(yùn)行時間間隔,默認(rèn)是120秒。
memoryStoreEvictionPolicy:當(dāng)達(dá)到maxElementsInMemory限制時,Ehcache將會根據(jù)指定的策略去清理內(nèi)存。默認(rèn)策略是LRU。你可以設(shè)置為 FIFO或是LFU。
clearOnFlush:內(nèi)存數(shù)量最大時是否清除。 -->
在SqlMapConfig.xml里設(shè)置,其實(shí)是默認(rèn)設(shè)置好的,另外兩個是設(shè)置延遲加載的沒影響,第三個默認(rèn)是true放這只是方便管理
<settings><!-- 打開延遲加載 的開關(guān) --><setting name="lazyLoadingEnabled" value="true" /><!-- 將積極加載改為消極加載即按需要加載 --><setting name="aggressiveLazyLoading" value="false" /><!-- 開啟二級緩存 --><setting name="cacheEnabled" value="true" /></settings>在UserMapper.xml里配置
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
此外User需要序列化,因?yàn)橛锌赡芫彺媸谴嬖谟脖P上。
此時就可以使用ehcache了。
?
轉(zhuǎn)載于:https://www.cnblogs.com/tuifeideyouran/p/4580775.html
總結(jié)
以上是生活随笔為你收集整理的mybatis+spring+c3p0+maven+ehcache的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。