2017-10-09 129 views
0

我有一個Spring引導應用程序,我在使用ehcache。該的Ehcache工作正常,如果我只有一個實體類,但如果我有超過1個實體類的Ehcache不工作,我得到以下錯誤: -Ehcache不適用於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] 

我的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> 

整個代碼可在 - https://github.com/iftekharkhan09/SpringCaching。任何幫助,高度讚賞。

回答

1

也許你有「關鍵衝突」,因爲你的緩存的名字是相同的。 我建議重新命名的高速緩存,就像這樣:

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

你也需要在ehcache.xml中

另一種方法來創建這些緩存的 - 在緩存中使用鍵,你可以看到它here

相關問題