簡體   English   中英

使用 ehcache 從 Spring Repository 中獲取 HashMap 而不是實體

[英]Fetch HashMap instead of entity from Spring Repository using ehcache

我正在使用 ehcache 在我的 spring 項目中緩存數據。

例如,如果您正在獲取數據 mst_store 表,那么目前我正在使用以下代碼

public interface MstStateRepository extends JpaRepository<MstState, Integer> {

@Override
@Cacheable("getAllState")
List<MstState> findAll();

可以看到findAll方法返回List<MstState>

但不是列出我需要的返回類型為 Map。 表示 key 作為 stateId 和 value 中的對象。

我可以在服務標簽中做這件事,但我需要為此編寫單獨的邏輯,如下所示

@Service 
class CacheService {
    @Autowired
    private MstStateRepository mstStateRepository;

    Map<Integer, MstState> cacheData = new HashMap<>();

    public List<MstState> findAllState() {
        List<MstState> mstStates = mstStateRepository.findAll();

        for (MstState mstState : mstStates) {
            cacheData.put(mstState.getStateId);
            cacheData.value(mstState);
        }
    }   
}

因此,我們可以直接從存儲庫中獲取 Map,而不是編寫單獨的邏輯。 請建議

您可以使用 Java 8 default方法,它允許您編寫可以被 jpa 覆蓋但不會被覆蓋的默認實現。 您還可以使用 java 8 中引入的流:

public interface MstStateRepository extends JpaRepository<MstState, Integer> {

    @Cacheable("getAllState")
    default Map<Integer, MstState> getAllState(){
        return findAll().stream()
            .collect(Collectors.toMap(
                MstState::getStateId, 
                UnaryOperator.identity()
            ));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM