0
点赞
收藏
分享

微信扫一扫

MyBatis-plus 3.5之前版本 处理存储json数据

MyBatis-plus 3.6之后支持集合泛型,不需要自定义TypeHandler

当前使用的是MyBatis-plus 3.5.2版本

一:如果是支持对象,直接用MP内置的Handler,JacksonTypeHandler或FastjsonTypeHandler

@TableField(typeHandler = FastjsonTypeHandler.class)

//@TableField(typeHandler = JacksonTypeHandler.class)

private Student student;

@TableName(value = "student" ,autoResultMap = true)

在表名映射上新增autoResultMap = true 属性,数据库字段student 中mysql中的json类型

二:如果是List集合,那么目前MP自带的Handler就不行,它只能处理对象,不能处理集合,需自定义Handler

分析原码:FastjsonTypeHandler支持Obect类型

MyBatis-plus 3.5之前版本 处理存储json数据_自定义

重写FastjsonTypeHandler类

public class JSONTypeHandler extends FastjsonTypeHandler {
private final Class<? extends Object> type;
public JSONTypeHandler(Class<?> type) {
    super(type);
    this.type = type;
}

@Override
protected List parse(String json) {
    return JSON.parseArray(json, type);
    //        return JSON.parseObject(json, type);
}
@Override
protected String toJson(Object obj) {
    return super.toJson(obj);
}
}

自定义具体转换实现类

public class StudentHandler extends JSONTypeHandler {
    public StudentHandler() {
       super(Student.class);
    }
}

在表映射新增自定义实现hanlder,@TableField(typeHandler = StudentHandler.class)

/**
    * 赛事详情
    */
@TableField(typeHandler = StudentHandler.class)
 private List<Student> students;

举报

相关推荐

0 条评论