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>
相关推荐
2301_789380491 小时前
vsc中使用DBHub-MCP连接云Mysql到vsc-copilot
数据库·mysql
杨DaB1 小时前
【MySQL】02 数据库的基本操作
数据库·mysql·oracle
m***66732 小时前
SQL 实战—递归 SQL:层级结构查询与处理树形数据
java·数据库·sql
昙鱼2 小时前
Markdown文件导入Milvus向量数据库完整指南
数据库·ai·milvus
A__tao2 小时前
gotool.top 的 SQL 转 Markdown
数据库·sql
Austindatabases3 小时前
基于SQLite如何设计应用程序,拆散,散,还的散!
数据库·sqlite
马克学长5 小时前
SSM面向乡村振兴服务的产教融合服务平台521gh(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·乡村振兴·ssm 框架·服务平台
u***27615 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
Y***K4345 小时前
MySQL网站
数据库·mysql
q***44816 小时前
postgresql链接详解
数据库·postgresql