簡體   English   中英

如何使用 JPA 在 static 方法中訪問數據庫?

[英]How to access DB in a static method using JPA?

我有一個 class 用於查詢 IMSI 的RegionCodeIMSI所屬的位置)。 這是我的代碼:

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IMSI {

    /**
     * Query RegionCode of IMSI
     */
    public static String queryRegionCode(String imsi) throws IMSIQueryException {
        // An HTTP call is here
        return HttpUtils.doQueryRequest();
    }

}

實用程序 class 工作正常。 由於HTTP請求過於頻繁,我打算將IMSIRegionCode的映射信息(不可變)保存到數據庫中。 所以我有以下代碼:

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IMSI {

    @Autowired
    private static RegionCodeCacheRepository repository;

    /**
     * Query RegionCode of IMSI
     */
    public static String queryRegionCode(String imsi) throws IMSIQueryException {
        // Query from DB preferentially
        if (repository.existsById(imsi)) return repository.getById(imsi).getRegionCode();
        // Call HTTP for query, if it does not exist in DB
        String regionCode = HttpUtils.doQueryRequest();
        // Save RegionCode and IMSI to DB
        RegionCodeCacheEntity entity = new RegionCodeCacheEntity();
        entity.setId(imsi);
        entity.setRegionCode(regionCode);
        repository.save(entity);
        // Return the RegionCode
        return regionCode;
    }

}

現在的麻煩是 Spring 不能幫我注入repository ,因為它是 static。我知道Spring static 注入是一個常見的問題,但這里我只是試圖以 static 的方法訪問數據庫,而不是尋找 87821360 8782136 的答案注射(那很糟糕,對吧?)。 我該如何解決我現在面臨的問題?

任何答案表示贊賞和感激:)


以下是一些額外的信息:

因為這些映射是固定的、不可變的,並且不會隨着時間的推移而失去信息價值,所以我選擇持久存儲它們。 我沒有選擇保存到 Redis、文件或 Java memory,因為它們需要比數據庫更多的持久存儲工作,而且由於這是一個小項目,我不想引入不必要的復雜性(如 Redis)。 這些都是我的考慮,可能是不好的或錯誤的。 不管怎樣,這種情況的最佳做法是什么?

再次感謝:)

您可以嘗試繞過 static 限制。

您的數據庫訪問進入 class 沒有 static 成員。 顯然,現在您需要這個 class 的一個實例。但您將其定義為 singleton,因此您的應用程序只有一個。

從您的 static 方法中,獲取對 singleton class 的引用,並運行執行數據庫查找的方法。

暫無
暫無

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

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