Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9120339
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T05:36:19+00:00 2026-06-17T05:36:19+00:00

Background Here is my working (simplified) GenericDao interface, which is implemented by any DomainDao

  • 0

Background

Here is my working (simplified) GenericDao interface, which is implemented by any DomainDao:

GenericDao.java

@NoRepositoryBean
public interface GenericDao<E extends Persistable<K>, K extends Serializable> extends JpaRepository<E, K> {

    public List<E> findAll();

    public E persist(E entity);

}

GenericDaoImpl.java

public class GenericDaoImpl<E extends Persistable<K>, K extends Serializable> extends SimpleJpaRepository<E, K> implements GenericDao<E, K> {

    private final JpaEntityInformation<E, ?> entityInformation;
    private final EntityManager em;
    private final Class<E> type;

    public GenericDaoImpl(JpaEntityInformation<E, ?> entityInformation, EntityManager em) {
        super(entityInformation, em);
        this.entityInformation = entityInformation;
        this.em = em;
        this.type = entityInformation.getJavaType();
    }

    @Override
    public List<E> findAll() {
        return super.findAll();
    }

    @Override
    @Transactional
    public E persist(E entity) {
        if (entityInformation.isNew(entity) || !EntityUtils.isPrimaryKeyGenerated(type) && !em.contains(entity)) {
            em.persist(entity);
        }
        return entity;
    }

}

For example, to manage the domains Foo and Bar, you just need to create two interfaces as follow:

FooDao.java

public interface FooDao extends GenericDao<Foo, Integer> {

}

BarDao.java

public interface BarDao extends GenericDao<Bar, Integer> {

}

The @Autowired annotation of Spring will automatically instantiate a GenericDaoImpl with the good entity and primary key types.


Problem

I’m now trying to add a caching process on my DAOs, using EhCache and the EhCache Spring Annotations model.

GenericDao.java

@NoRepositoryBean
public interface GenericDao<E extends Persistable<K>, K extends Serializable> extends JpaRepository<E, K> {

    @Cacheable(cacheName = "dao")
    public List<E> findAll();

    @TriggersRemove(cacheName = "dao")
    public E persist(E entity);

}

applicationContext.xml

<ehcache:annotation-driven cache-manager="ehCacheManager" />    
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />

ehcache.xml

<cache name="dao"
    eternal="false"
    maxElementsInMemory="10000"
    overflowToDisk="false"
    timeToIdleSeconds="86400"
    timeToLiveSeconds="86400"
    memoryStoreEvictionPolicy="LFU" />

The problem with the use of a GenericDao, is that the cache should manage each DomainDao independently of each other. For example, with the current configuration, if I call fooDao.findAll(), and then barDao.persist(new Bar()), the cache generated by fooDao.findAll() will be reset, since the same cache would have been used (i.e. <cache name="dao" />), while it shouldn’t.


Trails

I tried to implement my own CacheKeyGenerator, that will take into account the type of the calling DomainDao:

applicationContext.xml

<ehcache:annotation-driven cache-manager="ehCacheManager" default-cache-key-generator="daoCacheKeyGenerator" />    
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
<bean id="daoCacheKeyGenerator" class="myapp.dao.support.DaoCacheKeyGenerator" />

DaoCacheKeyGenerator.java

public class DaoCacheKeyGenerator implements CacheKeyGenerator<DaoCacheKey> {

    @Override
    public DaoCacheKey generateKey(MethodInvocation methodInvocation) {
        Class<?> clazz = methodInvocation.getThis().getClass().getInterfaces()[0];
        Method method = methodInvocation.getMethod();
        String methodName = method.getName();
        Class<?>[] parameterClasses = method.getParameterTypes();
        return new DaoCacheKey(clazz, methodName, parameterClasses);
    }

    @Override
    public DaoCacheKey generateKey(Object... data) {
        return null;
    }
}

DaoCacheKey.java

public class DaoCacheKey implements Serializable {

    private static final long serialVersionUID = 338466521373614710L;

    private Class<?> clazz;
    private String methodName;
    private Class<?>[] parameterClasses;

    public DaoCacheKey(Class<?> clazz, String methodName, Class<?>[] parameterClasses) {
        this.clazz = clazz;
        this.methodName = methodName;
        this.parameterClasses = parameterClasses;
    }

    @Override
    public boolean equals(Object obj) { // <-- breakpoint
        if (obj instanceof DaoCacheKey) {
            DaoCacheKey other = (DaoCacheKey) obj;
            if (clazz.equals(other.clazz)) {
                // if @TriggersRemove, reset any cache generated by a find* method of the same DomainDao
                boolean removeCache = !methodName.startsWith("find") && other.methodName.startsWith("find");
                // if @Cacheable, check if the result has been previously cached
                boolean getOrCreateCache = methodName.equals(other.methodName) && Arrays.deepEquals(parameterClasses, other.parameterClasses);
                return removeCache || getOrCreateCache;
            }
        }
        return false;
    }

    @Override
    public int hashCode() { // <-- breakpoint
        return super.hashCode();
    }

}

The problem with the above DaoCacheKey, is that the equals method get never called (the program never breaks at least), but the hashCode one does, so the algorithm can’t get applied.


Question

Has anyone already managed such a cache? If yes how? Does my try is relevant? If yes, how to make the equals method called, instead of the hashCode one? By extending an existing CacheKeyGenerator? If yes, which one?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T05:36:21+00:00Added an answer on June 17, 2026 at 5:36 am

    Here is the working solution I finally adopted. Just few precisions: my domains all implement the Persistable interface of Spring. Moreover, since I’m using reflection, I’m not sure the time saved by the caching process won’t be a bit reduced…

    applicationContext.xml

    <ehcache:annotation-driven cache-manager="ehCacheManager" default-cache-key-generator="daoCacheKeyGenerator" />    
    <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
    <bean id="daoCacheKeyGenerator" class="myapp.dao.support.cache.DaoCacheKeyGenerator" />
    

    DaoCacheKeyGenerator.java (using the gentyref library)

    public class DaoCacheKeyGenerator implements CacheKeyGenerator<DaoCacheKey> {
    
        @SuppressWarnings("unchecked")
        @Override
        public DaoCacheKey generateKey(MethodInvocation methodInvocation) {
            Method method = methodInvocation.getMethod();
            Class<? extends GenericDao<?, ?>> daoType = (Class<? extends GenericDao<?, ?>>) methodInvocation.getThis().getClass().getInterfaces()[0];
            Class<? extends Persistable<?>> domainType = getDomainType(daoType);
            String methodName = method.getName();
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object[] parameters = methodInvocation.getArguments();
            return new DaoCacheKey(domainType, methodName, parameterTypes, parameters);
        }
    
        @SuppressWarnings("unchecked")
        private Class<? extends Persistable<?>> getDomainType(Class<?> daoType) {
            Type baseDaoType = GenericTypeReflector.getExactSuperType(daoType, GenericDao.class);
            ParameterizedType parameterizedBaseDaoType = (ParameterizedType) baseDaoType;
            return (Class<? extends Persistable<?>>) parameterizedBaseDaoType.getActualTypeArguments()[0];
        }
    
        @Override
        public DaoCacheKey generateKey(Object... data) {
            return null;
        }
    
    }
    

    DaoCacheKey.java

    public class DaoCacheKey implements Serializable {
    
        private static final long serialVersionUID = 338466521373614710L;
    
        private Class<? extends Persistable<?>> domainType;
        private String methodName;
        private Class<?>[] parameterTypes;
        private Object[] parameters;
    
        public DaoCacheKey(Class<? extends Persistable<?>> domainType, String methodName, Class<?>[] parameterTypes, Object[] parameters) {
            this.domainType = domainType;
            this.methodName = methodName;
            this.parameterTypes = parameterTypes;
            this.parameters = parameters;
        }
    
        public Class<? extends Persistable<?>> getDomainType() {
            return domainType;
        }
    
        @Override
        public boolean equals(Object obj) {
            return this == obj || obj instanceof DaoCacheKey && hashCode() == obj.hashCode();
        }
    
        @Override
        public int hashCode() {
            return Arrays.hashCode(new Object[] { domainType, methodName, Arrays.asList(parameterTypes), Arrays.asList(parameters) });
        }
    
    }
    

    ehcache.xml

    <cache name="dao"
        eternal="false"
        maxElementsInMemory="10000"
        overflowToDisk="false"
        timeToIdleSeconds="86400"
        timeToLiveSeconds="86400"
        memoryStoreEvictionPolicy="LFU">
        <cacheEventListenerFactory class="myapp.dao.support.cache.DaoCacheEventListenerFactory" />
    </cache>
    

    DaoCacheEventListenerFactory.java

    public class DaoCacheEventListenerFactory extends CacheEventListenerFactory {
    
        @Override
        public CacheEventListener createCacheEventListener(Properties properties) {
            return new DaoCacheEventListener();
        }
    
    }
    

    DaoCacheEventListener.java

    public class DaoCacheEventListener implements CacheEventListener {
    
        @SuppressWarnings("unchecked")
        @Override
        public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
            DaoCacheKey daoCachekey = (DaoCacheKey) element.getKey();
            List<Class<? extends Persistable<?>>> impacts = getOneToManyImpacts(daoCachekey.getDomainType());
            for (DaoCacheKey daoCachedkey : (List<DaoCacheKey>) cache.getKeys()) {
                if (impacts.contains(daoCachedkey.getDomainType())) {
                    cache.remove(daoCachedkey);
                }
            }
        }
    
        @SuppressWarnings("unchecked")
        private List<Class<? extends Persistable<?>>> getOneToManyImpacts(Class<? extends Persistable<?>> domainType) {
            List<Class<? extends Persistable<?>>> impacts = new ArrayList<Class<? extends Persistable<?>>>();
            impacts.add(domainType);
            for (Method method : domainType.getDeclaredMethods()) {
                if (method.isAnnotationPresent(OneToMany.class)) {
                    ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType();
                    Class<? extends Persistable<?>> impactedDomainType = (Class<? extends Persistable<?>>) parameterizedType.getActualTypeArguments()[0];
                    if (!impacts.contains(impactedDomainType)) {
                        impacts.addAll(getOneToManyImpacts(impactedDomainType));
                    }
                }
            }
            return impacts;
        }
    
        @Override
        public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
        }
    
        @Override
        public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
        }
    
        @Override
        public void notifyElementExpired(Ehcache cache, Element element) {
        }
    
        @Override
        public void notifyElementEvicted(Ehcache cache, Element element) {
        }
    
        @Override
        public void notifyRemoveAll(Ehcache cache) {
        }
    
        @Override
        public void dispose() {
        }
    
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    
    }
    

    Hope that could help ;)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Ok, I need help. This is my first question here. Background: I am working
I have this query which works correctly in MySQL. More background on it here
Here is the working code i have: The text and background color property do
Really amateur question here - body background-gradient isn't working in chrome, very strange, I've
Here's the CSS code I'm working with: #navigation input#search_bar { background: url(images/searchbar.png) no-repeat; border:
Here is the coding in which hover is working inf firefox but not in
a little background here.I've been working with spring+hibernate(JPA+Session)+maven for while now.I'm used to Hibernate
Here is working example: http://jsfiddle.net/nnrgu/1/ And here i change to background-position:0px -70px and see
I have an Ul of item. I want to alternate there background color here
I have googled an serached a lot here about background runnin aps but have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.