Available in versions: Dev (3.21) | Latest (3.20) | 3.19 | 3.18 | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11
This documentation is for the unreleased development version of jOOQ. Click on the above version links to get this documentation for a supported version of jOOQ.
Custom data type conversion
Supported by ✅ Open Source Edition ✅ Express Edition ✅ Professional Edition ✅ Enterprise Edition
jOOQ supports a variety of built-in data types as well as user-defined types. If you prefer your own domain types(see also SQL domain types) to be used with your table columns or other column expressions, you can use jOOQ's org.jooq.Converter API.
A Converter allows for two-way conversion between two Java data types T and U. By convention, the T type corresponds to the built-in type in your database whereas the U type corresponds to your own user type. The Converter API is summarised here:
public interface Converter<T, U> extends Serializable {
/**
* Convert a database object to a user object
*/
U from(T databaseObject);
/**
* Convert a user object to a database object
*/
T to(U userObject);
/**
* The database type
*/
Class<T> fromType();
/**
* The user type
*/
Class<U> toType();
}
Such a Converter can be used in many parts of the jOOQ API. While they're most powerful when attached to generated code, you can also attach them to arbitrary expressions as follows:
record IntegerWrapper(Integer wrapped) {}
DataType<Integer> t = SQLDataType.INTEGER;
// This DataType can now be used everywhere in jOOQ. It will remember how to
// convert between Integer and the user type IntegerWrapper
DataType<IntegerWrapper> u = t.asConvertedDataType(Converter.of(
Integer.class,
IntegerWrapper.class,
IntegerWrapper::new,
IntegerWrapper::wrapped
));
// For example, you can attach it to a plain SQL template:
Field<IntegerWrapper> f1 = field("ID", u);
// Or you can coerce any expression to your type:
Field<IntegerWrapper> f2 = BOOK.ID.coerce(u);
Feedback
Do you have any feedback about this page? We'd love to hear it!