1. 演示表格准备
demo表
1 2 3 4 5 | CREATE TABLE `demo` ( `id` bigint NOT NULL AUTO_INCREMENT, `tag` json DEFAULT NULL , PRIMARY KEY (`id`) ) |
数据:
id | tag |
---|---|
1 | [3, 4, 5] |
2 | [“abc”] |
3 | [“a”, “b”, “c”] |
2. SQL操作JSON
2.1.精确查询
从数组中查询是否包含某个特定元素
注意 ,字符串必须使用单引号+双引号
1 2 3 4 | select * from demo where json_contains(tag, '"a"' ); id|tag | --+---------------+ 3|[ "a" , "b" , "c" ]| |
2.2.模糊查询
1 2 3 | select json_search(‘{“a”:“xyzf”,“b”:{“c”:“sdf”}} ',‘all' ,‘%f% ') select * from doc where json_search(tag,‘all' ,‘%d%') |
其他的不再赘述
3.mybatis-plus中操作JSON字段
3.1自带方法的JSON处理
实体类上要加上自动映射
1 | @TableName (value= "doc" ,autoResultMap = true ) |
json字段上加上json处理器
1 2 3 4 5 | @TableName (value= "doc" ,autoResultMap = true ) public class Doc{ @TableField (value= "tag" ,typeHandler = FastjsonTypeHandler. class ) private Set tag; } |
这样,使用mybatis-plus自带的数据库操作方法时,就可以自动映射了。自己写的方法或SQL不管用。
3.2 QueryWrapper查询的JSON处理
数组模糊查询,模糊查询tag字段数组中是否有指定的值。
1 2 | QueryWrapper wrapper = new QueryWrapper(); wrapper.isNotNull( "json_search(tag,'all',concat('%','" + param.getTag() + "','%'))" ); |
3.3 自定义SQL操作
查询结果需要自定义映射,json字段需要使用typeHandler。
1 2 | select * from doc where json_search(tag,'all',concat('%',#{param.searchKey},'%')) |
新增JSON中的元素,若已存在则不新增
1 2 3 4 5 6 7 | update doc set tag =json_Array_append(tag,'$',#{param.tag}) , update_time=update_time where doc_no in #{docNo} and !JSON_CONTAINS(tag,concat('"',#{param.tag},'"')) |
删除JSON中的元素,删除已存在的元素,元素不存在则不删除
1 2 3 4 5 6 7 8 | UPDATE doc SET tag = JSON_REMOVE(tag, JSON_UNQUOTE(JSON_SEARCH(tag, 'all', #{param.tag}))) WHERE JSON_SEARCH(tag, 'all',#{param.tag}) and doc_no in #{docNo} |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。