Alex
Alex

Reputation: 93

Mapping String to enum jooq

Is there a straightforward way to map a field in MySQL to an enum in JOOQ? The field is USER_STATUS, possible values are defined by

public enum Status {
  ACTIVE, INACTIVE, SUSPENDED
}

I tried to use forcedType:

<forcedType>
    <userType>com.mycompany.Status</userType>
    <expressions>USER_STATUS</expressions>
</forcedType>

However, this did not trigger any changes in the generated code. I tried the lower and upper case, prefixed and postfixed the column name (user_status) with '.*'. Nothing seems to work. What am I doing wrong?

Thanks!

Upvotes: 4

Views: 6372

Answers (1)

Lukas Eder
Lukas Eder

Reputation: 220842

The <forcedType/> element has several operation modes, each of which requires one additional child element:

Data type rewriting

In this case, you would need a <name/> element to map USER_STATUS columns to another data type. This doesn't work with enum types, though.

Applying a converter or binding

One way to map database types to your own <userType/> is by applying either a <converter> (i.e. org.jooq.Converter) or <binding/> (i.e. org.jooq.Binding). Use this approach to get full control over the conversion between the database type and your user type. You could also use the built-in org.jooq.impl.EnumConverter for this.

The EnumConverter works for ordinal mappings and 1:1 string to java.lang.Enum.name() mappings. If your enum values in the database have unmappable strings (e.g. containing whitespace), then you need to apply a manual mapping / converter.

Applying an enum converter (jOOQ 3.10+)

The simplest solution is to use an <enumConverter>true</enumConverter> flag on your <forcedType/>, if you do not have any special cases, which will also apply the org.jooq.impl.EnumConverter for you. This is also documented for the <forcedType/> element.

The same rules as for org.jooq.impl.EnumConverter apply.

Upvotes: 4

Related Questions