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>
相关推荐
luckys.one17 分钟前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
言之。2 小时前
Django中的软删除
数据库·django·sqlite
阿里嘎多哈基米3 小时前
SQL 层面行转列
数据库·sql·状态模式·mapper·行转列
抠脚学代码3 小时前
Ubuntu Qt x64平台搭建 arm64 编译套件
数据库·qt·ubuntu
小菜全4 小时前
基于若依框架Vue+TS导出PDF文件的方法
javascript·vue.js·前端框架·json
jakeswang4 小时前
全解MySQL之死锁问题分析、事务隔离与锁机制的底层原理剖析
数据库·mysql
Heliotrope_Sun4 小时前
Redis
数据库·redis·缓存
一成码农4 小时前
MySQL问题7
数据库·mysql
吃饭最爱4 小时前
JUnit技术的核心和用法
数据库·oracle·sqlserver
专注API从业者4 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python