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>
相关推荐
程序新视界35 分钟前
详解MySQL两种存储引擎MyISAM和InnoDB的优缺点
数据库·后端·mysql
半路_出家ren42 分钟前
设计一个学生管理系统的数据库
linux·数据库·sql·mysql·网络安全·数据库管理员
金仓拾光集3 小时前
筑牢风控生命线:金仓数据库替代MongoDB,重构证券融资融券业务的数据基石
数据库·mongodb·信创·1024程序员节·kingbasees·国产化替代
枫叶梨花3 小时前
实战:将 Nginx 日志实时解析并写入 MySQL,不再依赖 ELK
mysql·nginx·elk
那我掉的头发算什么3 小时前
【数据库】navicat的下载以及数据库约束
android·数据库·数据仓库·sql·mysql·数据库开发·数据库架构
纪伊路上盛名在3 小时前
如何批量获取蛋白质序列的所有结构域(domain)数据-2
数据库·人工智能·机器学习·统计·计算生物学·蛋白质
tuokuac4 小时前
虚拟机挂起,重启后主机连接不上虚拟机docker中的mysql?(docker网络状态假死)
网络·mysql·docker
2301_772093565 小时前
高并发webserver_interview
运维·服务器·数据库·后端·网络协议·mysql·wireshark
大G的笔记本6 小时前
MySQL 大表查询优化、超大分页处理、SQL 慢查询优化、主键选择
数据库·sql·mysql
Lear6 小时前
Redis 持久化机制
数据库