Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
MyBatis EnumUsingDbCodeTypeHandler using interface
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
public class EnumUsingDbCodeTypeHandler<E extends Enum<E> & EnumUsingDbCode> extends BaseTypeHandler<E> {
private final Class<E> type;
private final E[] enumConstants;
public EnumUsingDbCodeTypeHandler(Class<E> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
this.type = type;
this.enumConstants = type.getEnumConstants();
if (!type.isInterface() && this.enumConstants == null) {
throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.getDbCode());
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
String dbCode = rs.getString(columnName);
return rs.wasNull() ? null : getEnum(dbCode);
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String dbCode = rs.getString(columnIndex);
return rs.wasNull() ? null : getEnum(dbCode);
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String dbCode = cs.getString(columnIndex);
return cs.wasNull() ? null : getEnum(dbCode);
private E getEnum(String dbCode) {
.filter(e -> e.getDbCode().equals(dbCode))
.orElseThrow(() -> new IllegalArgumentException("Cannot convert " + dbCode + " to " + type.getSimpleName()));
public interface EnumUsingDbCode {
String getDbCode();
public enum ExampleEnum implements EnumUsingDbCode {
public String getDbCode() {

This comment has been minimized.

Copy link

@qb20nh qb20nh commented Oct 23, 2021


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment