2017-10-09 13 views
0

J'ai une application de démarrage Spring où j'utilise ehcache. Le Ehcache fonctionne bien si j'ai une seule classe d'entité, mais si j'ai plus de 1 entité classe le ehcache ne fonctionne pas et je reçois l'erreur suivante: -Ehcache ne fonctionne pas avec l'application de démarrage Spring

java.lang.ClassCastException: com.myapp.beans.Contact cannot be cast to com.myapp.beans.Department 
    at com.sun.proxy.$Proxy102.findOneById(Unknown Source) ~[na:na] 
    at com.myapp.service.impl.DepartmentServiceImpl.show(DepartmentServiceImpl.java:19) ~[classes/:na] 

Mon code Java: -

DepartmentRepository.java

@Repository 
public interface DepartmentRepository extends JpaRepository<Department, Integer> { 

    @Cacheable(value="appCache") 
    @Query("select d from Department d where d.id=:id") 
    Department findOneById(@Param("id") int id); 
} 

ContactRepository

@Repository 
public interface ContactRepository extends JpaRepository<Contact, Integer> { 

    @Cacheable(value = "appCache") 
    @Query("select c from Contact c where c.id=:id") 
    Contact findOneById(@Param("id") int id); 

} 

ehcache.xml

<ehcache> 
    <cache name="appCache" maxBytesLocalHeap="50m" timeToLiveSeconds="100"></cache> 
</ehcache> 

Le code complet est disponible à - https://github.com/iftekharkhan09/SpringCaching. Toute aide est grandement appréciée.

Répondre

1

Vous avez probablement des "collisions de clés", car les noms de votre cache sont identiques. Je suggère de renommer les caches, comme ceci:

@Cacheable(value="appCache1") 
    @Query("select d from Department d where d.id=:id") 
    Department findOneById(@Param("id") int id); 

@Cacheable(value = "appCache2") 
    @Query("select c from Contact c where c.id=:id") 
    Contact findOneById(@Param("id") int id); 

vous devez également créer chacun de ces caches dans ehcache.xml

Une autre façon - clé d'utilisation dans votre cache, vous pouvez lire à ce sujet here