Skip to main content

8.4 Enum Type Handler

dbVisitor automatically selects EnumTypeHandler for enum types, so no intervention is usually needed.

Object mapping with an enum field
public class User {
private UserType userType;

// getters and setters omitted
}
No special handling needed for queries and parameters
// Enum fields in query results are automatically converted
jdbc.queryForList("select * from users", User.class);

// Enum parameters are also handled automatically
User userInfo = ...;
jdbc.queryForList("select * from users where user_type = #{userType}", userInfo);
info

By default, EnumTypeHandler maps using the enum's name() value to match database fields (string-based).

Explicit Declaration​

Explicitly specify in parameter passing
jdbc.queryForList(
"select * from users where user_type = #{userType, typeHandler=net.hasor.dbvisitor.types.handler.string.EnumTypeHandler}",
userInfo
);
Explicitly specify in object mapping
public class User {
@Column(typeHandler = EnumTypeHandler.class)
private UserType userType;

// getters and setters omitted
}
  • EnumTypeHandler full class name: net.hasor.dbvisitor.types.handler.string.EnumTypeHandler

Map Numeric Values to Enums​

If the database stores numeric values, the enum needs to implement the EnumOfValue interface to convert between numbers and enum values.

public enum LicenseEnum implements EnumOfValue<LicenseEnum> {
Private(0),
AGPLv3(1),
GPLv3(2);

private final int type;

LicenseEnum(int type) {
this.type = type;
}

public int codeValue() {
return this.type;
}

public LicenseEnum valueOfCode(int codeValue) {
for (LicenseEnum item : LicenseEnum.values()) {
if (item.codeValue() == codeValue) {
return item;
}
}
return null;
}
}
  • The EnumOfValue interface is in the net.hasor.dbvisitor.types.handler.string package

Map Codes to Enums​

When the enum's name() cannot be used directly as the database mapping value, the enum can implement the EnumOfCode interface to customize string mapping logic.

public enum LicenseEnum implements EnumOfCode<LicenseEnum> {
Private("private_license"),
AGPLv3("agpl_v3"),
GPLv3("gpl_v3");

private final String code;

LicenseEnum(String code) {
this.code = code;
}

public String codeName() {
return this.code;
}

public LicenseEnum valueOfCode(String codeValue) {
for (LicenseEnum item : LicenseEnum.values()) {
if (item.codeName().equalsIgnoreCase(codeValue)) {
return item;
}
}
return null;
}
}
  • The EnumOfCode interface is in the net.hasor.dbvisitor.types.handler.string package
  • If the enum already has a default codeName() method (returning name()), you only need to override the valueOfCode method