<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>byteco.de &#187; Spring</title>
	<atom:link href="http://byteco.de/category/java/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://byteco.de</link>
	<description>In a world of 1s and 0s...are you a zero, or The One?</description>
	<lastBuildDate>Sun, 05 Feb 2012 05:44:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Integrating Spring and EHCache</title>
		<link>http://byteco.de/2010/01/26/integrating-spring-and-ehcache/</link>
		<comments>http://byteco.de/2010/01/26/integrating-spring-and-ehcache/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 16:15:37 +0000</pubDate>
		<dc:creator>shiv</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[ehcache]]></category>

		<guid isPermaLink="false">http://byteco.de/?p=875</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p>Using <a href="https://springmodules.dev.java.net/">Spring Modules</a> and <a href="http://ehcache.org/">EHCache</a>, one can transparently cache method results. Spring Modules uses a proxy which intercepts call to the method of bean; consults the cache to check if method was called with same parameters before, if so will return cached result.</p>
<p>EHCache is the actual provider of caching solution and Spring Module handles method interception and result storing in cache.<br />
<span id="more-875"></span><br />
Since I am using Maven2, so added following dependancies -</p>
<pre class="brush: xml">
        &lt;dependency&gt;
            &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt;
            &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
            &lt;version&gt;1.6.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springmodules&lt;/groupId&gt;
            &lt;artifactId&gt;spring-modules-cache&lt;/artifactId&gt;
            &lt;version&gt;0.9&lt;/version&gt;
        &lt;/dependency&gt;
</pre>
<p>My complete pom.xml -</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;groupId&gt;Spring&lt;/groupId&gt;
    &lt;artifactId&gt;Spring&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;version&gt;4.7&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-beans&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;cglib&lt;/groupId&gt;
            &lt;artifactId&gt;cglib&lt;/artifactId&gt;
            &lt;version&gt;2.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
            &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
            &lt;version&gt;1.6.6&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;version&gt;5.1.10&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-dbcp&lt;/groupId&gt;
            &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt;
            &lt;version&gt;1.2.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
            &lt;version&gt;3.0.0.RELEASE&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt;
            &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
            &lt;version&gt;1.6.1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springmodules&lt;/groupId&gt;
            &lt;artifactId&gt;spring-modules-cache&lt;/artifactId&gt;
            &lt;version&gt;0.9&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/project&gt;
</pre>
<p>Contact Table sql -</p>
<pre class="brush: sql">
 CREATE TABLE `contact` (
  `ID` int(15) NOT NULL AUTO_INCREMENT,
  `FIRSTNAME` varchar(50) DEFAULT NULL,
  `LASTNAME` varchar(50) DEFAULT NULL,
  `EMAIL` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `EMAIL` (`EMAIL`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
</pre>
<p>Adding ehcache namespace to Spring config file -</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xmlns:ehcache=&quot;http://www.springmodules.org/schema/ehcache&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd&quot;&gt;
...
&lt;/beans&gt;
</pre>
<p>Created ehcache.xml file in classpath.</p>
<pre class="brush: xml">
&lt;ehcache&gt;
    &lt;defaultCache
            maxElementsInMemory=&quot;500&quot; eternal=&quot;true&quot; overflowToDisk=&quot;false&quot; memoryStoreEvictionPolicy=&quot;LFU&quot;/&gt;
    &lt;cache name=&quot;contactCache&quot; maxElementsInMemory=&quot;500&quot; eternal=&quot;true&quot; overflowToDisk=&quot;false&quot;
           memoryStoreEvictionPolicy=&quot;LFU&quot;/&gt;
&lt;/ehcache&gt;
</pre>
<p>Adding caching to application-context.xml  &#8211; </p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xmlns:ehcache=&quot;http://www.springmodules.org/schema/ehcache&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd&quot;&gt;

    &lt;ehcache:config configLocation=&quot;classpath:ehcache.xml&quot; /&gt;

    &lt;ehcache:proxy id=&quot;contactDAO&quot; refId=&quot;contactDAOTarget&quot;&gt;
        &lt;ehcache:caching cacheName=&quot;contactCache&quot; methodName=&quot;findAll&quot;/&gt;
        &lt;ehcache:flushing cacheNames=&quot;contactCache&quot; methodName=&quot;createContact&quot; when=&quot;after&quot;/&gt;
    &lt;/ehcache:proxy&gt;

    &lt;bean id=&quot;contactDAOTarget&quot; class=&quot;byteco.de.spring.ContactDAOImpl&quot;&gt;
        &lt;property name=&quot;namedParameterJdbcTemplate&quot; ref=&quot;jdbcTemplate&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;datasource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;&gt;
        &lt;property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;username&quot; value=&quot;root&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;password&quot;/&gt;
        &lt;property name=&quot;initialSize&quot; value=&quot;5&quot;/&gt;
        &lt;property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/springjpa&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;jdbcTemplate&quot; class=&quot;org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate&quot;&gt;
        &lt;constructor-arg type=&quot;javax.sql.DataSource&quot; ref=&quot;datasource&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p>Here is my test class -</p>
<pre class="brush: java">
package byteco.de.spring;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.test.annotation.ExpectedException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.Assert.assertTrue;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = &quot;/application-context.xml&quot;)
public class ContactDAOTest {

    @Autowired
    ContactDAO contactDAO;

    @Test
    public void shouldCreateNewContact(){
         assertTrue(contactDAO.createContact(&quot;gabbar&quot;,&quot;singh&quot;,&quot;gabbar@singh.com&quot;));
         assertTrue(contactDAO.createContact(&quot;kalia&quot;,&quot;singh&quot;,&quot;kalia@singh.com&quot;));
    }

    @Test
    public void shouldReturnListOfContact(){
        assertTrue(contactDAO.findAll().size()&gt;0);
        assertTrue(contactDAO.findAll().size()&gt;0);
        assertTrue(contactDAO.findAll().size()&gt;0);
        // This will cause the cache to be cleared. refer to logs.
        assertTrue(contactDAO.createContact(&quot;samba&quot;,&quot;singh&quot;,&quot;samba@singh.com&quot;));
        assertTrue(contactDAO.findAll().size()&gt;0);
        assertTrue(contactDAO.findAll().size()&gt;0);
        assertTrue(contactDAO.findAll().size()&gt;0);
    }
}
</pre>
<p>Executed test shouldCreateNewContact first then shouldReturnListOfContact. Below is the console output -</p>
<pre class="brush: plain">
DEBUG [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor] - Autowiring by type from bean name &#039;byteco.de.spring.ContactDAOTest&#039; to bean named &#039;contactDAO&#039;
DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean &#039;org.springframework.aop.aspectj.AspectJPointcutAdvisor#0&#039;
DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean &#039;org.springframework.aop.aspectj.AspectJPointcutAdvisor#0&#039;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;null&gt;
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL query
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [select * from contact]
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Fetching JDBC Connection from DataSource
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to store the object &lt;[0. 1 gabbar singh , 1. 2 kalia singh ]&gt; in the cache using key &lt;2056181503|2056171012&gt; and model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Object was successfully stored in the cache
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;[0. 1 gabbar singh , 1. 2 kalia singh ]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;[0. 1 gabbar singh , 1. 2 kalia singh ]&gt;
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL update
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [insert into contact (firstname,lastname,email) values (?,?,?)]
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Fetching JDBC Connection from DataSource
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - SQL update affected 1 rows
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to flush the cache using model &lt;org.springmodules.cache.provider.ehcache.EhCacheFlushingModel@2dd59d3c[cacheNames={&#039;contactCache&#039;}, flushBeforeMethodExecution=false]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Cache has been flushed.
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;null&gt;
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL query
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [select * from contact]
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Fetching JDBC Connection from DataSource
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - Returning JDBC Connection to DataSource
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to store the object &lt;[0. 1 gabbar singh , 1. 2 kalia singh , 2. 3 samba singh ]&gt; in the cache using key &lt;2056181503|2056171012&gt; and model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Object was successfully stored in the cache
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;[0. 1 gabbar singh , 1. 2 kalia singh , 2. 3 samba singh ]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Attempt to retrieve a cache entry using key &lt;2056181503|2056171012&gt; and cache model &lt;org.springmodules.cache.provider.ehcache.EhCacheCachingModel@1531164[cacheName=&#039;contactCache&#039;, blocking=false, cacheEntryFactory=null]&gt;
DEBUG [org.springmodules.cache.provider.ehcache.EhCacheFacade] - Retrieved cache element &lt;[0. 1 gabbar singh , 1. 2 kalia singh , 2. 3 samba singh ]&gt;
</pre>
<p>Here are my DAO classes &#8211; </p>
<pre class="brush: java">
package byteco.de.spring;
import java.util.List;
public interface ContactDAO {
    boolean createContact(String firstName, String lastName, String email);
    List findAll();
}
</pre>
<pre class="brush: java">
package byteco.de.spring;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactDAOImpl implements ContactDAO {

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    public boolean createContact(String firstName, String lastName, String email) {
        Map&lt;String,String&gt; map = new HashMap&lt;String, String&gt;();
        map.put(&quot;firstname&quot;,firstName);
        map.put(&quot;lastname&quot;,lastName);
        map.put(&quot;email&quot;,email);
        int i = namedParameterJdbcTemplate.update(&quot;insert into contact (firstname,lastname,email) values (:firstname,:lastname,:email)&quot;, map);
        return i&gt;0;
    }

    public List findAll() {
        return namedParameterJdbcTemplate.query(&quot;select * from contact&quot;, (Map&lt;String, ?&gt;) null, new RowMapper() {
            public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                return i + &quot;. &quot; + resultSet.getString(1) + &quot; &quot; + resultSet.getString(2) + &quot; &quot; + resultSet.getString(3) + &quot; &quot;;
            }
        });
    }
}
</pre>
<p>We are caching the result of findAll and clearing cache when createContact is executed.</p>
]]></content:encoded>
			<wfw:commentRss>http://byteco.de/2010/01/26/integrating-spring-and-ehcache/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

