java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis-Plus处理Mysql Json字段

Mybatis-Plus处理Mysql Json类型字段的详细教程

作者:jasonspace2012

这篇文章主要给大家介绍了关于Mybatis-Plus处理Mysql Json类型字段的详细教程,Mybatis-Plus可以很方便地处理JSON字段,在实体类中可以使用@JSONField注解来标记JSON字段,同时在mapper.xml中使用json函数来操作JSON字段,需要的朋友可以参考下

概要

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

使用Json格式的好处:

整体实现流程

1、查看Mysql版本

SELECT VERSION();

2、创建mysql表

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `text` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

3、定义实体类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import lombok.Data;

@Data
//开启自动映射
@TableName(value = "test",autoResultMap = true)
public class Test {

    @TableId(type = IdType.AUTO)
    private Integer id;
	//定义Json字段handler
    @TableField(typeHandler = FastjsonTypeHandler.class)
    private JsonNode text;
}
import lombok.Data;
import java.io.Serializable;
@Data
public class JsonNode implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
}

4、定义Mapper、Service、ServiceImpl

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yiyou.base.entity.Test;

public interface TestMapper extends BaseMapper<Test> {
}
import com.baomidou.mybatisplus.extension.service.IService;
import com.yiyou.base.entity.Test;

public interface TestService extends IService<Test> {

    boolean insert(Test test);
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yiyou.base.entity.Test;
import com.yiyou.base.mapper.TestMapper;
import com.yiyou.base.service.TestService;
import org.springframework.stereotype.Service;

@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, Test> implements TestService {


    @Override
   public boolean insert(Test test) {
        return this.saveOrUpdate(test);
    }
}

5、Controller层实现

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.yiyou.base.entity.Test;
import com.yiyou.base.service.TestService;
import com.yiyou.model.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


@Slf4j
@Api(tags = "test")
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestService testService;

    @ApiOperation("新增")
    @PostMapping("/save")
    public R<Boolean> save(@RequestBody Test test) {
        return R.ok(testService.insert(test));
    }

    @ApiOperation("根据Id获取对象")
    @GetMapping("/getById/{id}")
    public R<Test> getById(@PathVariable("id") Integer id) {
        return R.ok(testService.getById(id));
    }

    @ApiOperation("根据Id删除")
    @DeleteMapping("/deleteById/{id}")
    public R<Boolean> deleteById(@PathVariable("id") Integer id) {
        return R.ok(testService.removeById(id));
    }

    @ApiOperation("条件查询")
    @PostMapping("/findList")
    public R<List<Test>> findList(@RequestBody Test 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());
        return R.ok(queryWrapper.list());
    }

技术细节

SELECT * FROM TEST WHERE text -> '$[*].name' like '%测%'

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

SELECT * FROM TEST WHERE text -> '$[1].name' like '%测%'
SELECT * FROM TEST WHERE text -> '$.name' = '测试'
SELECT * FROM TEST WHERE JSON_CONTAINS(text,JSON_OBJECT('name', '测试'))
SELECT id, text -> '$[*].name' AS name FROM TEST;
SELECT id, JSON_EXTRACT( text, '$[*].name' ) AS name FROM TEST;
SELECT id, JSON_UNQUOTE(text, '$[*].name' ) AS name FROM TEST;
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());//精确查询

总结 

到此这篇关于Mybatis-Plus处理Mysql Json类型字段的文章就介绍到这了,更多相关Mybatis-Plus处理Mysql Json字段内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文