Search code examples
javajpaspring-data-jpapersistencestatic-methods

How to access DB in a static method using JPA?


I have a class for querying RegionCode(where the IMSI belongs) of IMSI. Here is my code:

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

}

The utility class works fine. Since the HTTP requests are too frequent, I intend to save the mapping information (immutable) of IMSI and RegionCode to the database. So I have the following code:

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

}

The trouble now is that Spring can't inject the repository for me because it's static. I know Spring static injection is a common question, but here I am just trying to access the database in a static method instead of looking for an answer to static injection(that's bad, right?). How can I solve the problem I am facing now?

Any answer is appreciated and thankful :)


The following is some extra information:

Because these mappings are fixed, immutable and they won't lose their information value over time, I choose to store them persistently. I didn't choose to save to Redis, files, or Java memory, as they require more work for persistent storage than databases, and since this is a small project, I don't want to introduce unnecessary complexity (like Redis). These are all my considerations, and probably they are bad or wrong. Whatever, what is the best practice for this scenario?

Thanks again :)


Solution

  • You could try to circumvent the static limitation.

    Your DB access goes into a class that has no static members. Obviously now you need an instance of this class. But you define it as singleton so there is one and only one for your application.

    From your static method, get a reference to the singleton class and run the method that performs the DB lookup.