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>
相关推荐
赵渝强老师1 小时前
【赵渝强老师】管理MongoDB的运行
数据库·mongodb
A仔不会笑1 小时前
MySQL面试篇——性能优化
java·数据库·mysql·面试·性能优化
梦幻编织者2 小时前
python使用django搭建图书管理系统
数据库·python·django
考虑考虑2 小时前
MySQL中的DATE_FORMAT时间函数
数据库·后端·mysql
SelectDB技术团队2 小时前
云原生时代的架构革新,Apache Doris 存算分离如何实现弹性与性能双重提升
大数据·数据库·云原生·doris·存算分离
杭州刘同学3 小时前
autogen studio如何修改数据库为mysql
mysql·autogen
星迹日3 小时前
MySQL : 数据库和表操作
数据库·mysql·数据类型··
2302_799525743 小时前
【Hadoop】如何理解MapReduce?
数据库·hadoop·mapreduce
已是上好佳3 小时前
介绍一下Qt中的事件过滤
java·服务器·数据库
梵法利亚4 小时前
Ubuntu-docker安装mysql
mysql·ubuntu·docker