解决mybatis在mysql中使用json类型查询问题

前置

  • mybatisplus
  • mysql 8.x

问题

当数据库中存在json格式的数据时,使用mybatisplus自带api能够查到json数据,但是自定义查询则会忽略json格式的数据

  • 数据库片段


  • 表中 wx_profile 的 json数据
{"sex": 0, "city": "", "openid": "", "country": "", "unionId": "", "language": "zh_CN", "nickname": "jabberwocky", "province": "", "subscribe": null, "headimgurl": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTK5cOQ6f0CkBHSAql1fsu5Kvh9Viaf0zhOV45ZYGy2yhdTg8KsesyibkO3yk31C4Br0AY8u1yQq6exw/132", "routineOpenid": "ocRYS46YYckkwAWrOfZA9NOAb0sY", "subscribeTime": null}
  • domain片段



问题复现

  • 自定义查询语句


  • 查询结果(无wxProfile属性)

问题分析

  • 在mybatis自定义查询时,json格式的数据常规无法直接进行映射,需要指定一个TypeHandler才能够正常映射。

解决方法

  • 使用@Results注解对返回的column(列)和property(属性)进行引导映射即可


    @Select("select * from `yx_user` where wx_profile is not null limit 1")
    @Results(
            @Result(column = "wx_profile",property = "wxProfile",typeHandler = FastjsonTypeHandler.class)
    )
   YxUser testAll();
  • 修复后的查询结果
原文链接:,转发请注明来源!