Hibernate / MyBatis Interview questions
Explain how to implement a custom TypeHandler in MyBatis?
A TypeHandler controls how MyBatis converts between a Java type and a JDBC type during parameter binding and result mapping; a custom TypeHandler is needed when a Java type doesn't have built-in support, or when the default conversion behavior isn't what a specific column requires — a common example being mapping a Java enum to a specific database column representation.
public class StatusTypeHandler extends BaseTypeHandler<Status> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Status parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter.getCode()); } @Override public Status getNullableResult(ResultSet rs, String columnName) throws SQLException { String code = rs.getString(columnName); return code == null ? null : Status.fromCode(code); } // additional getNullableResult overloads for column index and CallableStatement }
Extending BaseTypeHandler<T> and implementing its abstract methods covers both directions of the conversion: setNonNullParameter handles converting a Java object into the JDBC value sent in a bound parameter, while the getNullableResult overloads handle converting a raw JDBC column value back into the Java type when reading a result set.
Once implemented, a custom TypeHandler is registered either globally (in mybatis-config.xml via <typeHandlers>, applying automatically to every column of the matching Java type) or explicitly per column (using the typeHandler attribute on a specific <result> or parameter reference), giving control over whether the custom conversion applies broadly or only in specific, targeted places.
More Related questions...