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 小时前
Django学习笔记二:数据库操作详解
数据库·django
编程老船长1 小时前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
Json_181790144801 小时前
商品详情接口使用方法和对接流程如下
大数据·json
全栈师2 小时前
SQL Server中关于个性化需求批量删除表的做法
数据库·oracle
Data 3172 小时前
Hive数仓操作(十七)
大数据·数据库·数据仓库·hive·hadoop
BergerLee2 小时前
对不经常变动的数据集合添加Redis缓存
数据库·redis·缓存
程序员大金2 小时前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql
gorgor在码农2 小时前
Mysql 索引底层数据结构和算法
数据结构·数据库·mysql
-seventy-3 小时前
SQL语句 (MySQL)
sql·mysql
bug菌¹3 小时前
滚雪球学Oracle[6.2讲]:Data Guard与灾难恢复
数据库·oracle·data·灾难恢复·guard