0


Mybatis-Plus处理Mysql Json类型字段

文章目录

概要

Mysql 5.7.8开始支持Json对象和Json数组,但在Mysql 8版本中使用Json性能更佳。

使用Json格式的好处:

  1. 无须预定义字段:字段可以无限拓展,避免了ALTER ADD COLUMN的操作,使用更加灵活。
  2. 处理稀疏字段:避免了稀疏字段的NULL值,避免冗余存储。
  3. 支持索引:相比于字符串格式的JSON,JSON类型支持索引做特定的查询优化。

整体实现流程

  1. 查看Mysql版本
SELECT VERSION();

在这里插入图片描述
2、创建mysql表

CREATETABLE`test`(`id`int(11)NOTNULLAUTO_INCREMENT,`text` json DEFAULTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8mb4;

在这里插入图片描述
3、定义实体类

importcom.baomidou.mybatisplus.annotation.IdType;importcom.baomidou.mybatisplus.annotation.TableField;importcom.baomidou.mybatisplus.annotation.TableId;importcom.baomidou.mybatisplus.annotation.TableName;importcom.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;importlombok.Data;@Data//开启自动映射@TableName(value ="test",autoResultMap =true)publicclassTest{@TableId(type =IdType.AUTO)privateInteger id;//定义Json字段handler@TableField(typeHandler =FastjsonTypeHandler.class)privateJsonNode text;}
importlombok.Data;importjava.io.Serializable;@DatapublicclassJsonNodeimplementsSerializable{privateInteger id;privateString name;privateInteger age;}

4、定义Mapper、Service、ServiceImpl

importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom.yiyou.base.entity.Test;publicinterfaceTestMapperextendsBaseMapper<Test>{}
importcom.baomidou.mybatisplus.extension.service.IService;importcom.yiyou.base.entity.Test;publicinterfaceTestServiceextendsIService<Test>{booleaninsert(Test test);}
importcom.baomidou.mybatisplus.extension.service.impl.ServiceImpl;importcom.yiyou.base.entity.Test;importcom.yiyou.base.mapper.TestMapper;importcom.yiyou.base.service.TestService;importorg.springframework.stereotype.Service;@ServicepublicclassTestServiceImplextendsServiceImpl<TestMapper,Test>implementsTestService{@Overridepublicbooleaninsert(Test test){returnthis.saveOrUpdate(test);}}

5、Controller层实现

importcom.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;importcom.yiyou.base.entity.Test;importcom.yiyou.base.service.TestService;importcom.yiyou.model.R;importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.*;importjava.util.List;importjava.util.Objects;@Slf4j@Api(tags ="test")@RestController@RequestMapping("/test")publicclassTestController{@AutowiredprivateTestService testService;@ApiOperation("新增")@PostMapping("/save")publicR<Boolean>save(@RequestBodyTest test){returnR.ok(testService.insert(test));}@ApiOperation("根据Id获取对象")@GetMapping("/getById/{id}")publicR<Test>getById(@PathVariable("id")Integer id){returnR.ok(testService.getById(id));}@ApiOperation("根据Id删除")@DeleteMapping("/deleteById/{id}")publicR<Boolean>deleteById(@PathVariable("id")Integer id){returnR.ok(testService.removeById(id));}@ApiOperation("条件查询")@PostMapping("/findList")publicR<List<Test>>findList(@RequestBodyTest test){LambdaQueryChainWrapper<Test> queryWrapper =  testService.lambdaQuery();
        queryWrapper
                .eq(Objects.nonNull(test.getId()),Test::getId,test.getId())//                .apply(Objects.nonNull(test.getText()),"text -> '$.name' LIKE CONCAT('%',{0},'%')",test.getText().getName()).apply(Objects.nonNull(test.getText()),"text -> '$.age' = {0}", test.getText().getAge());//                .like(Objects.nonNull(test.getText()),Test::getText,test.getText());returnR.ok(queryWrapper.list());}

技术细节

  • Json字段模糊查询
SELECT*FROM TEST WHEREtext->'$[*].name'like'%测%'

或 上面的"*"也可以使用下标

SELECT*FROM TEST WHEREtext->'$[1].name'like'%测%'
  • Json字段精确查询
  • 使用箭头函数
SELECT*FROM TEST WHEREtext->'$.name'='测试'
  • 使用 JSON_CONTAINS
SELECT*FROM TEST WHERE JSON_CONTAINS(text,JSON_OBJECT('name','测试'))
  • 查询json中的name字段
SELECT id,text->'$[*].name'AS name FROM TEST;
  • 使用JSON_EXTRACT 函数,带双引号
SELECT id, JSON_EXTRACT(text,'$[*].name')AS name FROM TEST;
  • 使用 JSON_UNQUOTE 函数,不带双引号
SELECT id, JSON_UNQUOTE(text,'$[*].name')AS name FROM TEST;
  • 查询Json字段中所有的值,用 “*”
SELECT id,text->'$[*].*'AS name FROM TEST;

Mybatis Plus使用LambdaQueryChainWrapper查询

 提示:使用apply方法拼接sql片段,apply 是可以通过占位符的形式,传入多个参数。

例如:

LambdaQueryChainWrapper<Test> queryWrapper =  testService.lambdaQuery();
        queryWrapper
.apply(Objects.nonNull(test.getText()),"text -> '$.name' LIKE CONCAT('%',{0},'%')",test.getText().getName())//模糊查询.apply(Objects.nonNull(test.getText()),"text -> '$.age' = {0}", test.getText().getAge());//精确查询
标签: mysql json mybatis

本文转载自: https://blog.csdn.net/chou19900418/article/details/133126550
版权归原作者 jasonspace2012 所有, 如有侵权,请联系我们删除。

“Mybatis-Plus处理Mysql Json类型字段”的评论:

还没有评论