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
Custom data type Converter
Supported by ✅ Open Source Edition ✅ Express Edition ✅ Professional Edition ✅ Enterprise Edition
A converted data type is a simple DataType<U<
where a Converter<T, U>
converts from some Built-in data types to a custom data type. The simplest way to get a DataType<U<
reference is by calling:
dataType.asConvertedDataType(converter)
Where a org.jooq.Converter
must implement at least these four methods:
public interface Converter<T, U> { // Your conversion logic goes into these two methods, that can convert // between the database type T and the user type U in both directions: U from(T databaseObject); T to(U userObject); // You need to provide Class instances for each type, too: Class<T> fromType(); Class<U> toType(); }
Or, using a specific example:
record Email(String email) {} // Using a simpler, functional API: Converter<String, Email> emailConverter = Converter.of( String.class, Email.class, // Converting String -> Email Email::new, // Converting Email -> String Email::email ); DataType<Email> emailType = VARCHAR.asConvertedDataType(emailConverter);
In most practical cases, the DataType<U<
does not need to be denoted like this. Instead, a re-usable Converter
class is attached to the generated EMAIL
columns throughout the schema using forced types configuration. However, when using plain SQL, this API usage can be useful:
// Plain SQL template based Field<Email> f1 = DSL.field("my_table.my_email_column", emailType); // Name based Field<Email> f2 = DSL.field(name("my_table", "my_email_column"), emailType);
In many cases, converters are single use and single direction only (e.g. fetching only). In those cases, there exists convenience API that is much less verbose to use, see ad-hoc converters for details.
Feedback
Do you have any feedback about this page? We'd love to hear it!