Question

I'm using Java 1.6 and Hibernate 3.6.10.Final. I need to check the contents of several database tables against enums built into our application. (The database tables tend to get values added and deleted occasionally and nobody tells the developers.) So on startup I'd like to do something like this:

for (service myService : ListOfServices() ) {
    enum MyEnum = GoGetCorrespondingEnum(myService);
    Map<Character, String> databaseMap = myService.findAll();
    if (databaseMap.size() != MyEnum.values().length) {
        logger.error("Enum is out of sync with database tableand must be fixed!");
    }
}

The catch is, in the second line, I don't know how to get the corresponding enum for the service I'm looking at. Can anyone suggest a method?

Était-ce utile?

La solution

Add a common method to all your service classes where each service can return the enum that it is related to.

public Class<? extends Enum<?>> getEnumType() {
    return MyEnum.class;
}

Then in your code that verifies the number of values in the enum for a given service use

myService.getEnumType().getEnumConstants().length;

Autres conseils

You could do something like this:

private static final String[] SERVICE_NAMES = { "ServiceA", "ServiceB" };

private List<String> getCorrespondingValuesFor(service) {
    List<String> values = new ArrayList<String>();
    for (String serviceName : SERVICE_NAMES) {
        if ("ServiceA".equals(myService.class.name)) {
            for (EnumForServiceA value : EnumForServiceA.values()) {
                values.add(value.name());
            }
            break;
        }
    }
    return allowedValues;
}

And then use it in the code you showed (but you should check for the content, not only the length):

for (Service myService : ListOfServices()) {
    List<String> supportedValues = getCorrespondingValuesFor(myService);
    List<String> usedValues = getListOfUsedValues(); /*using findAll() someway*/
    if (!supportedValues.containsAll(usedValues)) {
        logger.error("Enum is out of sync with database tableand must be fixed!");
    }
}

Important:

Since it happens (and I don't consider that "logging a message telling the developers to update the code to support new values" a solution to the problem), I would suggest other ways to handle it:

  • Restrict the user to add only values in the enum (see here), but it wouldn't handle direct changes to the database
  • Restructure your code structure and/or data mapping to handle that occurrences better, not needing code changes
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top