Help with Java Generics -- creating a small "framework"

Hey --

TL/DR -- In Java, I'm struggling to understand how to create an object instance of a generic type without first knowing the type.

So, before I delve down into this, know that I'm trying to understand generics a bit better and maybe a bit of reflection a bit more so I can figure out how to do this myself before I start relying on frameworks such as Hibernate to do the kinds of things that I'm doing.

The story so far:

Until recently, we've had an POJO-backed datastore that was fine for everyone except a couple of folks who want everything in the database (solely for the purpose of having it in a database.) Recently, the winds of politics have changed and the "get everything in the database" folks are in the ascendant.

The data model includes several Enum types. Because "in the database" is necessary, simply storing the ordinal values of the Enum members in the DB isn't workable. So, storing each enum in its own table (dimension table?) with assigned lookup ID's is probably best. So, this is what I've done so far (classes made up to protect the stupid, of course):

Code:
public enum WidgetStatus {
  PENDING,
  ACTIVE,
  BACK_ORDERED,
  INACTIVE,
  ARCHIVED
}

public class Widget {
  id int;
  String name;
  WidgetStatus status;
}

which, to me, leads to DDL that looks like:

Code:
create table widget_status (
  widget_status_id int not null primary key,
  label varchar(12) not null
);

create table widget (
  widget_id int not null primary key,
  name varchar(50) not null,
  widget_status_id int references widget_status ( widget_status_id )
);

So, in my code, I need to initialize a coder-decoder mechanism for each of these table-backed enum types. To that end I created EnumCodec:

Code:
public class EnumCodec<T> {   // is there something better to use for an enum other than passing in Class<?>?
  private Map<T, Integer> encoder = new HashMap<>();
  private Map<Integer, T> decoder = new HashMap<>();

  public void addMapping(T t, Integer i) { 
    encoder.put(t, i);
    decoder.put(i, t);
  }

  public T decode(Integer i) { 
    return decoder.get(i);
  }

  public Integer encode(T type) { 
    return encoder.get(type);
  }
}

I started out hand-coding all the DDL/DML queries to create tables and fetch the data from the DB to create each codec:

Code:
public class EnumDAO { 
  private final Connection conn;
  public EnumDAO(Connection conn) {
    this.conn = conn;
  }

  public EnumCodec<WidgetStatus> buildWidgetStatusCodec() throws SQLException {
    EnumCodec<WidgetStatus> codec = new EnumCodec();
    try (Statement st = conn.createStatement()) {
      try (ResultSet rs = st.executeQuery("select * from widget_status")) {
        while(rs.next()) {
          WidgetStatus v = WidgetStatus.fromValue(rs.getString("label"));
          int index = rs.getInt("widget_status_id");
          codec.addMapping(v, index);
        }
      }
    }
    return codec;
 }
 .
 // one of these per enum type >.<
 .

But that got tedious, so I figured I could use some reflection + convention and came up with a mechanism to automatically generate the DDL/DML based on the name of the enumeration class:

Code:
class EnumSqlStuff { // awesome name, right?

  private static final Map<Class, EnumSqlStuff> ENUM_TUPLES = new ConcurrentHashMap<>();

  String createTableSql;
  String insertSql;
  String selectSql;

  EnumSqlStuff(Class<?> e) {
    if (e.isEnum()) {
      init(e);
    } else {
      throw IllegalArgumentException("can't create codec for non-enum type");
    }
  }

  private <E> void init(Class<?> e) {
    String enumCodecName = e.getSimpleName();
    // de-camel-case/normalize class name for use as a table name & field name
    StringBuilder sb = new StringBuilder();
    boolean firstChar = true;
    for (char ch : enumCodecName.toCharArray()) {
      final char loweredCh = Character.toLowerCase(ch);
      if (loweredCh != ch) {
        if (!firstChar) {
          sb.append("_");
        }
      }
      sb.append(loweredCh);
      firstChar = false;
    }
    final String tableName = sb.toString();
    final String idFieldName = tableName + "_id";
    // find longest enum::name() for varchar(width)
    int maxLength = -1;
    for (Object x : e.getEnumConstants()) {
      Enum xxx = (Enum) x;
      maxLength = Math.max(maxLength, xxx.name().length());
    }
    this.createTableSql = "create table " + tableName + " ( " + idFieldName + " int not null primary key, value varchar(" + maxLength + ") not null";
    this.insertSql = "insert into " + tableName + " ( " + idFieldName + ", value ) values (?, ?)"; 
    this.selectSql = "select " + idFieldName + ", value from " + tableName;
  }

  public static EnumSqlStuff sqlForEnum(Class<?> e) {
    if (!ENUM_TUPLES.containsKey(e)) {
      EnumSqlStuff x = new EnumSqlStuff(e);
      ENUM_TUPLES.put(e, x);
    }
    return ENUM_TUPLES.get(e);
  }
}

So I have mechanisms to create the tables and insert the enum constants into their tables and a mechanism to fetch the data. What I don't know how to do
is effectively:

Code:
private static final Class<?>[] ENUMS = {
  WidgetStatus.class, ... // other enum classes here
};

static Map<Class<?>, EnumCodec<?> codecRegistry = new HashMap<>();   // what's the right thing for the generic parameters here?

static { 
  EnumDAO dao = new EnumDAO(conn); // :sigh: where am I going to get a DB connection in the static context? I'll work that out, I guess
  for (Class c : ENUMS) {
    EnumCodec<?> newCodec = dao.buildCodecFor(c);
  }
}

So, this is needed in the EnumDAO:

Code:
public Enum<Class<? extends Enum>> buildCodecFor(Class<?> aClass) throws SQLException {
  EnumSqlStuff sql = EnumSqlStuff.sqlForEnum(aClass);
  if (sql != null) {
    try (Statement st = conn.createStatement()) {
      try (ResultSet rs = st.executeQuery(sql.selectSql)) {
        EnumCodec<?> codec = new EnumCodec<>();
        while(rs.next()) {
          int id = rs.getInt(1);
          String label = rs.getString(2);
          codec.addMapping(id, label);
        }
        return codec;
      }
    }
  }
}

So, I try to nail all this together, but the generic types are wrong in many places. For example, I try to widgetStatusCodec.encode(w.getStatus()); and the compiler complains about the type mismatch between the declared and used parameter types "incompatible types: WidgetStatus cannot be converted to CAP#1 where CAP#1 is a fresh type-variable: CAP#1 extends Enum from capture of ? extends Enum."

Ideas to what I'm messing up? Am I trying too hard and missing something or have I not done enough and need even more infrastructure to make this work? I think I'm on the cusp, but I don't know how/quite understand how to finagle the generic types to make it all work together. I remember something from Java Essentials -- Josh Bloch's PECS mnemonic, but I guess I don't understand it/generics well enough to know where to plug them in.

Thanks for getting this far!
 
D

Deleted member 43669

Guest
You have two options:

1) Use an *existing* ORM
2) Do not use an ORM

You are going with "write an ORM", which I wouldn't really recommend to anyone.

1) means use Hibernate (ugh), or any of the not-quite-an-ORM Java libraries (jOOQ is my favorite. I don't know if iBatis is still a thing or there is some new hotness out there).

2) means writing "non-generic" code. You write a function that executes some *SPECIFIC* SQL and builds objects out of the query result and returns them. Raw JDBC is annoying. Spring JDBC and some bits of the Spring Framework provide nice tools to do this. Again, I'm a bit out of the loop of what's new and nice in the Java ecosystem.

...

As for Java generics, the standard recommendation used to be this: http://www.angelikalanger.com/GenericsF ... csFAQ.html ... and it probably still is...
 

Lt_Storm

Ars Tribunus Angusticlavius
21,346
Subscriptor++
First, never ever ever generate SQL with stringbuilers. That is just asking for some kind of SQL injection attack. You need something smarter. Hibernate is a good idea, even if it is often a pain in the ass.

Second, these are Java enums, they can and should have methods on them. When I was working with such mechanisms, we duplicated things like the ids of enums in both the database and the code. It looked something like:

Code:
public enum WidgetStatus {
  PENDING(0, "Pending"),
  ACTIVE(1, "Active"),
  BACK_ORDERED(2, "Back_ordered"),
  INACTIVE(3, "Inactive"),
  ARCHIVED(4, "archived);
  
  private int id;
  private String Code;

  WidgetStatus(int id, String code){
    this.id = id;
    this.code = code;
  }

  public String getLabel(DAO dao) {
    // get the label from the dao; alternately, load such things at startup and store them in a variable.
  }
}

Third, your EnumCodec<T> class needs to remember what type it was made for. This will become important when you are doing lookups using classes.

Code:
public class EnumCodec<T extends Enum> {
  private Map<T, Integer> encoder = new HashMap<>();
  private Map<Integer, T> decoder = new HashMap<>();
  private Class<T> klass;

  public EnumCodec(Class<T> klass) {
    this.klass = klass;
  }

  public void addMapping(T t, Integer i) {
    encoder.put(t, i);
    decoder.put(i, t);
  }

  public T decode(Integer i) {
    return decoder.get(i);
  }

  public Integer encode(T type) {
    return encoder.get(type);
  }
}

Fourth: even if you don't duplicate such information, there really is no need for your EnumDAO to have a buildXCodec method for each enum type. You should be able to make a generic one by binding each enum type to a table name and then using the class objects to get the data.

Code:
public Enum DatabaseEnumTypeMappings {
  WidgetStatus(WidgetStatus.getClass, "widget_status");

  @Getter private final Class type;
  @Getter private final String table;
  
  DatabaseEnumTypeMappings(Class enumType, String enumTable) {
    this.type = enumType;
    this.table = enumTable;
  }
}

public class EnumDAO {
  private final Connection conn;
  public EnumDAO(Connection conn) {
    this.conn = conn;
  }

  public EnumCodecs buildCodecs() {  
      // you need an EnumCodecs rather than a list to handle the type
      // erasure problems that lists bring in.
    EnumCodecs codecs = new EnumCoecs()
    for (DatabaseEnumTypeMapping mapping: DatabaseEnumTypeMapping.values()) {
      codecs.add(buildCodec(type, type.getClass()));
    }
  }

  public EnumCodec<T> buildCodec(DatabaseEnumTypeMappings type, Class<T> enumClass) throws SQLException { 
      // this "pass in the class (or TypeReference)" thing is pretty common in 
      // reflective Java generic code even when you don't use it because of type 
      // erasure.  You need it to actually keep the types around at runtime.
    if (type.getClass() != enumClass) {
      Throw new Error("you done fucked up");
    }
    EnumCodec<T> codec = new EnumCodec();
    // use the type object to build the codec.  If you need lists of fields, add them to it.
    return codec;
 }

Finally, in order to deal with type erasure, it often makes sense to use TypeReferences or TypeLiterals rather than Classes. Look at how Jackson and Guice handle that.

PS: you will have to forgive my compile errors, I am both a bit rusty and not using an IDE.
 
Okay, so I took what you wrote and made it work.

The only short-coming that I can't seem to overcome -- and I kind doubt that it can be overcome -- is that when building a Widget in the dao/mapper, I have to explicity cast the WidgetStatus value:

Code:
public Widget fetchWidgetById(int id) throws SQLException {
  try (PreparedStatement ps = conn.prepareStatement("select widget_id, name, widget_status_id from widget where widget_id = ?")) {
    int f = 1;
    ps.setInt(f++, id);
    try (ResultSet rs = ps.executeQuery()) {
      if (rs.next()) {
        Widget w = new Widget();
        w.setId(rs.getInt(1));
        w.setName(rs.getString(2));
        w.setStatus((WidgetStatus) codecs.get(WidgetStatus.class).decode(rs.getInt(3)));
        return w;
      } else { 
        return null;
      }
    } 
  }
}

That w.setStatus((WidgetStatus) codecs.get(WidgetStatus.class).decode(rs.getInt(3))) seems kind of unwieldy and echo-ey.
 

HappyBunny

Ars Legatus Legionis
13,232
Subscriptor
What's the signature of codecs.get()? That seems like something you shouldn't need to cast in the caller.

It seems like you should be able to have something like:
Code:
public <T extends Enum<T>> EnumCodec<T> get(Class<T> clazz) {
   // return whatever lookup
}

It's possible that you would need a cast within the get() method, but there you can have some assurance that it's correct since that class controls the mapping.
 
What's the signature of codecs.get()? That seems like something you shouldn't need to cast in the caller.

It seems like you should be able to have something like:
Code:
public <T extends Enum<T>> EnumCodec<T> get(Class<T> clazz) {
   // return whatever lookup
}

It's possible that you would need a cast within the get() method, but there you can have some assurance that it's correct since that class controls the mapping.

I was only returning EnumCodec ... this seems to have made the compiler happy. Will test it!
 
Looks a bit like going around your elbow…

Give WidgetStatus a static method fromOrdinal(int).

I mean, sure, that will help the in-memory bit and give me a decoder, but I still need an encoder and the values still need to be normalized in the db. Unless I'm missing something you're implying.

Also, return Optional<Widget> from the fetch method instead of null.

Good idea. I don't use Optional<T> enough.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,346
Subscriptor++
What's the signature of codecs.get()? That seems like something you shouldn't need to cast in the caller.

It seems like you should be able to have something like:
Code:
public <T extends Enum<T>> EnumCodec<T> get(Class<T> clazz) {
   // return whatever lookup
}

It's possible that you would need a cast within the get() method, but there you can have some assurance that it's correct since that class controls the mapping.

I was only returning EnumCodec ... this seems to have made the compiler happy. Will test it!

Yep, that's a mistake. When using generics, you should basically never have an unqualified generic type. Moreover, you should almost never use <?> as the qualifier. Usually there should be a type variable and often some kind of extends or super clause.