Mybatis/mybatis-plus map mysql json type fields directly to objects

created at 07-30-2021 views: 55


Main attributes:

1. typeHandler: But to customize the processing class, you must inherit the BaseTypeHandler; data reading and writing will be filtered by this class

<resultMap id="getTestConfigByCode" type="com.xxxxx.entity.TestConfig">
    <id column="id" jdbcType="NUMERIC" property="id"/>
    <result column="test_json" javaType=""
            property="testJson" />

Custom typeHandler class

public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private              Class<T>     clazz;

    public JsonTypeHandler(Class<T> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = clazz;

    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));

    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getObject(columnName), clazz);

    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getObject(columnIndex), clazz);

    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getObject(columnIndex), clazz);

    private T toObject(Object content, Class<T> clazz) {
        if (content == null) {
            return null;
        return JSON.parseObject(content.toString(), clazz);



mybatis-plus is much more convenient, the framework has implemented a custom typeHandler class

1. The typeHandler attribute can be configured in xml like mybatis:

typeHandler = "com.baomidou.mybatisplus.extension.handlers.jacksonTypeHandler"

2. Annotations can be used in entity classes:

@TableField(typeHandler = JacksonTypeHandler.class)
created at:07-30-2021
edited at: 07-30-2021: