mysql存json数据时的查询办法

很多时候mysql的一列当中存的是json格式的数据,这时候如果要查询某个key对应的值的时候要如何查询呢,这里记录一种查询方法:

json列的值:

{"InventoryMainTypeCode": 1, "InventoryMainTypeName": "GOOD"}

现在要查询InventoryMainTypeCode为xxx或者InventoryMainTypeName为xxx的数据:(这里以springboot+mybatis为例子)

代码:

请求类:

java 复制代码
Query query = new Query();
java 复制代码
@Data
public class Query implements Serializable {

    
    private Map<String, Object> featureMap = new HashMap<>();

    public void setFeature(String feature) {
        if (StringUtils.isNotBlank(feature)) {
            featureMap = JSON.parseObject(feature, Map.class);
        }
    }

    public void addFeature(String key, Object value) {
        if (StringUtils.isBlank(key)) {
            return;
        }
        this.featureMap.put(key, value);
    }
    public void addFeatureMap(Map<String, Object> featureMaps) {
        if (MapUtils.isNotEmpty(featureMaps)){
            this.featureMap.putAll(featureMaps);
        }
    }
}

在代码中将key添加到Feature中:

java 复制代码
query.addFeature(DicConst.InventoryMainTypeCode.name(), 1);
List<ResultDTO> dTOS = dictionaryManager.queryDicByParam(query);

mapper文件:

java 复制代码
 List<CnbDictionaryDO> queryDicByParam(CnbDictionaryQuery query);

xml:

xml 复制代码
  <select id="queryDicByParam" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from
        <include refid="Table_Name"/>
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
         
            <if test="featureMap != null and featureMap.size > 0">
                <foreach collection="featureMap" index="key" item="value">
                    <if test="value != null">
                        <![CDATA[and feature->'$.${key}' = #{value}]]>
                    </if>
                </foreach>
            </if>
        </where>
    </select>
相关推荐
数据狐(Datafox)10 分钟前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
FYKJ_201036 分钟前
【毕设分享】基于Web的校园兼职信息发布与申请系统07059
前端·vue.js·spring boot·mysql·typescript·spark·课程设计
adinnet202639 分钟前
客服与工单:响应时长与满意度问数
数据库·人工智能
文人sec1 小时前
MYSQL:insert...select:为什么锁源表的所有行和间隙?怎么最快地复制一张表?
数据库·python·mysql
oradh2 小时前
Oracle联机日志文件损坏故障总结
数据库·oracle·oracle联机日志文件损坏
IvorySQL2 小时前
PostgreSQL 日报|8 字节 TOAST 值支持(9 月 16 日)
数据库·人工智能·postgresql
实验室管理云平台2 小时前
北京盛元广通推疾控中心实验室管理系统,提升检测效率
数据库·python
极限实验室3 小时前
INFINI Easysearch 向量搜索实战(一)
数据库·搜索引擎
枫叶丹43 小时前
数据库上 Kubernetes 后,KES-Operator 如何简化集群运维
数据库
蓝速科技3 小时前
数字人一体机芯片选型:RK3576 与 X86 场景化对比指南丨蓝速科技
大数据·运维·数据库·人工智能·科技