Mybatis自定义TypeHandler实现数据库Json数组转List<T>对象

2,417 阅读1分钟

实现功能

在开发过程中经常会遇到将整个JSON数据当作一个字段存到数据库中的情况,但是我们在对应实体表中又不想用一个String去接收,如下图,数据库t_user表中有一个address字段,存的是一个JSON数组,TUserEntity实体中使用List

对象去接收,这时就需要自定义TypeHanlder帮我们定义入库和出库时的JSON序列化和反序列化。

image.png

@Data
@TableName("t_user")
public class TUserEntity  implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    @TableField(typeHandler = AddressListTypeHandler.class)
    private List<Address> address;
}
    ```
@Data
public class Address implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String name;
}
```

定义抽象List处理TypeHandler,List中可能还存入其它类型数据

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JsonUtils.toJson(parameter));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return rs.wasNull() ? null : JsonUtils.readList(rs.getString(columnName), specificType());
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.wasNull() ? null : JsonUtils.readList(rs.getString(columnIndex), specificType());
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cs.wasNull() ? null : JsonUtils.readList(cs.getString(columnIndex), specificType());
    }

    protected abstract TypeReference<List<T>> specificType();

定义AddressListTypeHandler类 ,如果有其它类继承ListTypeHandler就可以了

@MappedTypes({List.class})
public class AddressListTypeHandler extends  ListTypeHandler<Address> {
    @Override
    protected TypeReference<List<Address>> specificType() {
        return new TypeReference<List<Address>>() {
        };
    }
}

jaskson中JsonUtils.readList()方法,也可使用fastjson JSON.parseObject(content, this.specificType())


public static <T> List<T> readList(String json, TypeReference<List<T>> tTypeReference) {
    if (json == null || "".equals(json)) {
        return null;
    }
    try {
        return mapper.readValue(json,tTypeReference);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

测试结果查询

image.png