Mybatis Plus MySql json类型操作

SpringBoot 2.7.18 集成 Mybatis Plus + Druid

  1. 在数据库表定义json字段;
  2. 在实体类加上@TableName(autoResultMap = true)
  3. 在JSON字段映射的属性加上@TableField(typeHandler = JacksonTypeHandler.class);
    image
    image

条件查询

@Test
void jsonQueryWapperTest() {
    String nickName = "李四";
    String role = "普通用户22";
    LambdaQueryChainWrapper<DemoInfo> queryWrapper = demoService.lambdaQuery();
    queryWrapper.apply(StrUtil.isNotEmpty(role), "JSON_CONTAINS(roles,JSON_OBJECT('name', {0}))", role);
    List<DemoInfo> list = queryWrapper.list();
    System.out.println("Result => " + PojoUtil.pojoToJson(list));
}

MySqlJosnTypeHandler

@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MySqlJosnTypeHandler extends AbstractJsonTypeHandler<Object> {

    public MySqlJosnTypeHandler(Class<?> type) {
        super(type);
    }

    public MySqlJosnTypeHandler(Class<?> type, Field field) {
        super(type, field);
    }

    @Override
    public Object parse(String json) {
        return JSON.parseObject(json, this.getFieldType());
    }

    @Override
    public String toJson(Object obj) {
        return JSON.toJSONString(obj);
    }

}

posted @ 2024-11-05 23:45  VipSoft  阅读(23)  评论(0编辑  收藏  举报