Hi Lukas,
After sending my e-mail, I thought of various ideas. I had one that
could simplify the whole issue of enums and more.
But first, let me explain something I found which is not about enums
but which happens to be covered by what I have in mind.
In our application, we do not use the sql Date objects. Instead, we
have our own class, and because of the number of dates we keep in
memory (think time series) we keep a cache of those dates.
When using jOOQ, we would have to manually transform our Date objects
to the sql dates when making a jOOQ call, and vice versa when parsing
the record.
What if jOOQ could apply a transformation not just for enums but also
on those other objects?
1. Let's start with a type mapper interface:
interface TypeMapper<T, U> {
public T to(U x);
public U from(T e);
public SQLDataType getDataType(T e);
}
2. In the generator, let's define certain columns of certain tables to
use type mapping:
MyTable1.MyDateColumn: com.xx.CustomDate
MyTable2.MyOtherDateColumn: com.xx.CustomDate
MyTable2.MyEnum: com.xx.SomeEnum
3. The generator declares the field as a mapped type.
public final
org.jooq.TableField<test.generated.tables.records.MyDateColumnRecord,
CustomDate> MY_DATE_COLUMN = createField("MyDateColumn",
SQLDataType.createMappedType(CustomDate.class), this);
4. In the code, the user configures the Settings with the right binding:
Settings settings = new Settings();
TypeMapper customDateMapper = new TypeMapper<com.xx.CustomDate,
java.sql.Date>() {
public com.xx.CustomDate to(java.sql.Date d) {
return xxx;
}
public java.sql.Date from(com.xx.CustomDate d) {
return xxx;
}
public SQLDataType getDataType(T e) {
return SQLDataType.DATE;
}
};
settings.map(MyTable1.MyDateColumn, customDateMapper);
settings.map(MyTable2.MyOtherDateColumn, customDateMapper);
TypeMapper myEnumMapper = new TypeMapper<com.xx.SomeEnum, Integer>() {
public SomeEnum to(Integer i) {
return xxx;
}
public Integer to(SomeEnum e) {
return xxx;
}
public SQLDataType getDataType(T e) {
return SQLDataType.SMALLINT;
}
}
settings.map(MyTable2.MyEnum, myEnumMapper);
The mapping configuration is up to the user, and can be tweaked if
needed (cache handling, same custom type with different mapping logic
depending on column, etc.). The user can place the mapping code
wherever he wants, and can implement enums the way he likes because he
controls the mapping.
When jOOQ tries to map a value and a mapper cannot be found, an
exception is thrown. This is not a problem because to start using a
mapped type the user would have had to define the mapping in the first
place.
Please, let me know what you think of this version :)
-Christopher