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):
which, to me, leads to DDL that looks like:
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:
I started out hand-coding all the DDL/DML queries to create tables and fetch the data from the DB to create each codec:
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:
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:
So, this is needed in the EnumDAO:
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!
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!