Caching using Spring and Ehcache

Configure EhCache Cache Manager

package com.example.cache;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;

@Configuration
@EnableCaching
public class EhChacheConfiguration {
	
	@Bean
	public EhCacheManagerFactoryBean ehCahceFactory(){		
		EhCacheManagerFactoryBean ehCache = new EhCacheManagerFactoryBean();
		ehCache.setConfigLocation(new ClassPathResource("ehcache.xml"));
		ehCache.setCacheManagerName("customerCache");
		ehCache.setShared(true);
		return ehCache;
	}
	
	@Bean
	public EhCacheCacheManager cachceManager(EhCacheManagerFactoryBean ehCahceFactory){
		EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
		ehCacheCacheManager.setCacheManager(ehCahceFactory.getObject());
		return ehCacheCacheManager;
	}
}

EhCache Configuration

<ehcache 
	xsi:noNamespaceSchemaLocation="ehcache.xsd" 
	updateCheck="true" 
	monitoring="autodetect" 
	dynamicConfig="true"
	maxBytesLocalHeap="150M"	
	>
	<diskStore path="java.io.tmpdir"/>	

	<cache name="customers"
	      maxBytesLocalHeap="40M"
	      eternal="false"
	      timeToIdleSeconds="300"
	      overflowToDisk="true"
	      maxEntriesLocalDisk="1000"
	      diskPersistent="false"
	      diskExpiryThreadIntervalSeconds="120"
	      memoryStoreEvictionPolicy="LRU"/>	 	      

</ehcache>

Cache Customer Service ~ Cached and CacheEvict

package com.example.jpa;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.service.CustomerService;
import com.example.model.Customer;
import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.TriggersRemove;

@Repository
@Qualifier("jpaRepository")
@Transactional(readOnly = true)
public class JpaCustomerService implements CustomerService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional(readOnly = true)
    @Cacheable(cacheName="CustomerCache")
    public Customer getCustomerById(BigInteger id) {
        return this.entityManager.find(Customer.class, id);
    }

    @Override
    @Transactional
    @CacheEvict(value = { "CustomerCache", "CustomerCache" }, allEntries = true, beforeInvocation = false)
    public Customer createCustomer(String fn, String ln) {
        Customer newCustomer = new Customer();
        newCustomer.setFirstName(fn);
        newCustomer.setLastName(ln);
        this.entityManager.persist(newCustomer);
        return newCustomer;
    }
   
    @Override
    @Cacheable(cacheName="CustomerCache")
	public Collection<Customer> getAllCustomers() {
		 CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
	     CriteriaQuery<Customer> criteriaBuilderQuery = criteriaBuilder.createQuery(Customer.class);
	     CriteriaQuery<Customer> customerCriteriaQuery = criteriaBuilderQuery.select(
	      criteriaBuilderQuery.from(Customer.class));
	     customerCriteriaQuery.orderBy(criteriaBuilder.asc(customerCriteriaQuery.from(Customer.class).get("id")));
	     return this.entityManager.createQuery(customerCriteriaQuery).getResultList();
	}

	@Override
	@Transactional
	@TriggersRemove(cacheName="CustomerCache", removeAll=true)
	public void deleteCustomer(BigInteger id) {
		this.entityManager.remove(this.entityManager.find(Customer.class, id));
	}
}

Advertisements

One Comment on “Caching using Spring and Ehcache

  1. Did you success making it 100% java config, even the EhCache configuration?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: