简体   繁体   中英

Ehcache not working with Spring boot application

I have a Spring boot application where i am using ehcache. The Ehcache is working fine if i have only one entity class but if i have more than 1 entity class the ehcache is not working and i am getting the below error:-

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]

My Java Code :-

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>

The entire code is available at - https://github.com/iftekharkhan09/SpringCaching . Any help is highly appreciated.

Probably you have "key collisions", because your cache's names are identical. I suggest to rename the caches, like this:

@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);

Also you have to create each of these caches in ehcache.xml

Another way - use key in your cache, you can read about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM