Plugins, type handlers and code generation
The extension points. Type handlers teach MyBatis about your column types; interceptors let you rewrite what the framework does; the generator writes the boring 80 % of a mapper layer for you.
Custom type handlers
A TypeHandler<T> converts one Java type to and from a JDBC value. You implement
four methods: one setter and three getters (by column name, by index, and from a callable
statement).
A code-backed enum
Storing enum.name() is fine until the database has legacy short codes.
public enum UserStatus {
ACTIVE("A"), SUSPENDED("S"), DELETED("D");
private final String code;
UserStatus(String code) { this.code = code; }
public String getCode() { return code; }
public static UserStatus fromCode(String code) {
for (UserStatus status : values()) {
if (status.code.equals(code)) {
return status;
}
}
throw new IllegalArgumentException("Unknown status code: " + code);
}
}
package com.bitsnippets.shop.handler;
import com.bitsnippets.shop.domain.UserStatus;
import org.apache.ibatis.type.*;
import java.sql.*;
@MappedTypes(UserStatus.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class UserStatusTypeHandler extends BaseTypeHandler<UserStatus> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
UserStatus parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, parameter.getCode());
}
@Override
public UserStatus getNullableResult(ResultSet rs, String columnName)
throws SQLException {
String code = rs.getString(columnName);
return code == null ? null : UserStatus.fromCode(code);
}
@Override
public UserStatus getNullableResult(ResultSet rs, int columnIndex)
throws SQLException {
String code = rs.getString(columnIndex);
return code == null ? null : UserStatus.fromCode(code);
}
@Override
public UserStatus getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
String code = cs.getString(columnIndex);
return code == null ? null : UserStatus.fromCode(code);
}
}
BaseTypeHandler handles the null cases, so those four methods only see non-null values.
A JSON/JSONB column
package com.bitsnippets.shop.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.*;
import java.sql.*;
@MappedJdbcTypes(value = JdbcType.OTHER, includeNullJdbcType = true)
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final Class<T> type;
// MyBatis calls this constructor when the handler is generic
public JsonTypeHandler(Class<T> type) {
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, T parameter,
JdbcType jdbcType) throws SQLException {
try {
ps.setObject(i, MAPPER.writeValueAsString(parameter), Types.OTHER);
} catch (Exception e) {
throw new SQLException("Cannot serialise " + type.getSimpleName(), e);
}
}
@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parse(rs.getString(columnName));
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parse(rs.getString(columnIndex));
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parse(cs.getString(columnIndex));
}
private T parse(String json) throws SQLException {
if (json == null) {
return null;
}
try {
return MAPPER.readValue(json, type);
} catch (Exception e) {
throw new SQLException("Cannot deserialise " + type.getSimpleName(), e);
}
}
}
<resultMap id="productMap" type="Product">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="attributes" column="attributes"
typeHandler="com.bitsnippets.shop.handler.JsonTypeHandler"/>
</resultMap>
<insert id="insert">
INSERT INTO product (name, attributes)
VALUES (#{name},
#{attributes, typeHandler=com.bitsnippets.shop.handler.JsonTypeHandler})
</insert>
Annotate with @MappedTypes and scan the package
(mybatis.type-handlers-package) for automatic registration, declare the handler
per column for one-off use, or register it explicitly in <typeHandlers>.
Per-column declaration always wins.
Interceptor plugins
| Type | Interceptable methods | Typical use |
|---|---|---|
Executor | update, query, flushStatements, commit, rollback, getTransaction, close, isClosed | Timing, query counting, cache control |
ParameterHandler | getParameterObject, setParameters | Encryption, audit fields |
ResultSetHandler | handleResultSets, handleOutputParameters | Decryption, masking |
StatementHandler | prepare, parameterize, batch, update, query | Pagination, SQL rewriting, tenant filters |
A slow-query logger
package com.bitsnippets.shop.plugin;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
@Intercepts({
@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "update",
args = {MappedStatement.class, Object.class})
})
public class SlowQueryPlugin implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(SlowQueryPlugin.class);
private long thresholdMillis = 200;
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
long started = System.nanoTime();
try {
return invocation.proceed();
} finally {
long millis = (System.nanoTime() - started) / 1_000_000;
if (millis >= thresholdMillis) {
log.warn("Slow statement {} took {} ms", ms.getId(), millis);
}
}
}
@Override
public void setProperties(Properties properties) {
this.thresholdMillis =
Long.parseLong(properties.getProperty("thresholdMillis", "200"));
}
}
Since MyBatis 3.5.x, Interceptor has a default plugin(Object target)
implementation that calls Plugin.wrap, so you no longer need to override it.
@Configuration
public class MyBatisPluginConfig {
@Bean
public ConfigurationCustomizer slowQueryCustomizer() {
return configuration -> {
SlowQueryPlugin plugin = new SlowQueryPlugin();
Properties props = new Properties();
props.setProperty("thresholdMillis", "250");
plugin.setProperties(props);
configuration.addInterceptor(plugin);
};
}
}
A multi-tenant filter
Rewriting SQL in a StatementHandler plugin is powerful and easy to get wrong.
This one appends a tenant predicate to every select, using reflection to reach the immutable
BoundSql.
@Intercepts(@Signature(type = StatementHandler.class, method = "prepare",
args = {Connection.class, Integer.class}))
public class TenantPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler handler = (StatementHandler) invocation.getTarget();
MetaObject meta = SystemMetaObject.forObject(handler);
MappedStatement ms =
(MappedStatement) meta.getValue("delegate.mappedStatement");
if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
BoundSql boundSql = handler.getBoundSql();
String tenantId = TenantContext.currentTenant();
if (tenantId != null && !boundSql.getSql().contains("tenant_id")) {
String rewritten = boundSql.getSql()
+ " AND tenant_id = '" + sanitise(tenantId) + "'";
meta.setValue("delegate.boundSql.sql", rewritten);
}
}
return invocation.proceed();
}
private String sanitise(String tenantId) {
if (!tenantId.matches("[A-Za-z0-9_-]{1,40}")) {
throw new IllegalStateException("Illegal tenant id");
}
return tenantId;
}
}
String-appending to SQL reintroduces injection risk — note the strict whitelist above.
A naive " AND tenant_id = ..." also breaks on queries with
GROUP BY, ORDER BY, UNION or no WHERE at
all. For anything beyond a proof of concept, parse the SQL properly (JSqlParser) or use a
maintained library such as MyBatis-Plus.
Stored procedures
<!-- IN and OUT parameters -->
<select id="calculateBonus" statementType="CALLABLE" parameterType="map">
{ call calculate_bonus(
#{userId, mode=IN, jdbcType=BIGINT},
#{year, mode=IN, jdbcType=INTEGER},
#{bonus, mode=OUT, jdbcType=DECIMAL},
#{message, mode=OUT, jdbcType=VARCHAR}
) }
</select>
<!-- a procedure returning a cursor -->
<select id="topCustomers" statementType="CALLABLE">
{ call top_customers(
#{limit, mode=IN, jdbcType=INTEGER},
#{result, mode=OUT, jdbcType=CURSOR,
javaType=java.sql.ResultSet, resultMap="customerMap"}
) }
</select>
Map<String, Object> params = new HashMap<>();
params.put("userId", 42L);
params.put("year", 2026);
reportMapper.calculateBonus(params); // OUT values land in the map
BigDecimal bonus = (BigDecimal) params.get("bonus");
String message = (String) params.get("message");
MyBatis Generator
MBG reverse-engineers tables into POJOs, mapper interfaces and XML. It is excellent for the repetitive CRUD layer over a large legacy schema, and unnecessary for a ten-table service.
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.2</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.3</version>
</dependency>
</dependencies>
</plugin>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="shop" targetRuntime="MyBatis3DynamicSql">
<property name="javaFileEncoding" value="UTF-8"/>
<jdbcConnection driverClass="org.postgresql.Driver"
connectionURL="jdbc:postgresql://localhost:5432/shop"
userId="shop_app"
password="change-me"/>
<javaModelGenerator targetPackage="com.bitsnippets.shop.domain"
targetProject="src/main/java"/>
<sqlMapGenerator targetPackage="com.bitsnippets.shop.mapper"
targetProject="src/main/resources"/>
<javaClientGenerator type="ANNOTATEDMAPPER"
targetPackage="com.bitsnippets.shop.mapper"
targetProject="src/main/java"/>
<table tableName="app_user" domainObjectName="User"/>
<table tableName="customer_order" domainObjectName="Order"/>
<table tableName="product" domainObjectName="Product"/>
</context>
</generatorConfiguration>
mvn mybatis-generator:generate
Generate into a dedicated package and never edit the output — the next run overwrites it. Put your interesting queries in a separate mapper that extends or complements the generated one.
The MyBatis Dynamic SQL library
A separate, type-safe DSL for building statements in Java. It is the default target of newer MBG runtimes and pairs well with a codebase that dislikes XML.
import static com.bitsnippets.shop.mapper.UserDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;
SelectStatementProvider statement =
select(id, userName, email)
.from(appUser)
.where(status, isEqualTo("ACTIVE"))
.and(createdAt, isGreaterThan(cutoff))
.orderBy(userName)
.limit(25)
.build()
.render(RenderingStrategies.MYBATIS3);
List<User> users = mapper.selectMany(statement);
Where should a plugin that adds pagination to every query intercept?
prepare runs just before the PreparedStatement is created, which is
the last point where the SQL string can still be rewritten. By the time parameters are
being set, the statement is already compiled.