Search code examples
javaandroidenumsormlite

How to make Generic Enum as OrmLite Column


I'm trying to minimize some of the work I'm going to have to do by "generifying" my lookup tables. They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is). Here's the abstract LookupRecord class

public abstract class LookupRecord<T extends Enum<T>> extends DatabaseRecord {
    public static final String TYPE_FIELD_NAME = "type";

    @DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
    private T type;

    public LookupRecord(T type) {
        this.type = type;
    }

    public T getType() {
        return type;
    }
}

So whenever I try to initialize the Dao for any of the lookup tables I get the following error:

java.sql.SQLException: Field FieldType:name=type,class=LookupRecord improperly configured as type com.j256.ormlite.field.types.EnumStringType@5e80d5


Solution

  • They are all going to have int id as primary key but I'd also like them to have the ability to be searched by their "type" (whatever the Enum value is).

    @DatabaseField(unique = true, columnName = TYPE_FIELD_NAME)
    private T type;
    

    Yeah this isn't going to work because of type erasure. When ORMLite goes to investigate the class in question using reflection, it tries to lookup the enum constants for this field. All it gets is the type Enum and not the specific concrete Enum class from the sub-class. Unfortunately that error message is less than helpful pointing that out.

    When the class is configured, all it knows is that it's an enum. It doesn't know which enum it is so it can't configure the field correctly or create instances of the object with an appropriate enum field there.