概要
Mysql 5.7.8開始支持Json對象和Json數(shù)組,但在Mysql 8版本中使用Json性能更佳。
使用Json格式的好處:
- 無須預(yù)定義字段:字段可以無限拓展,避免了ALTER ADD COLUMN的操作,使用更加靈活。
- 處理稀疏字段:避免了稀疏字段的NULL值,避免冗余存儲。
- 支持索引:相比于字符串格式的JSON,JSON類型支持索引做特定的查詢優(yōu)化。
整體實現(xiàn)流程
- 查看Mysql版本
SELECT VERSION();
2、創(chuàng)建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層實現(xiàn)
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("根據(jù)Id獲取對象")
@GetMapping("/getById/{id}")
public R<Test> getById(@PathVariable("id") Integer id) {
return R.ok(testService.getById(id));
}
@ApiOperation("根據(jù)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());
}
技術(shù)細(xì)節(jié)
- Json字段模糊查詢
SELECT * FROM TEST WHERE text -> '$[*].name' like '%測%'
或 上面的"*"也可以使用下標(biāo)
SELECT * FROM TEST WHERE text -> '$[1].name' like '%測%'
-
Json字段精確查詢
-
使用箭頭函數(shù)
SELECT * FROM TEST WHERE text -> '$.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 函數(shù),帶雙引號
SELECT id, JSON_EXTRACT( text, '$[*].name' ) AS name FROM TEST;
- 使用 JSON_UNQUOTE 函數(shù),不帶雙引號
SELECT id, JSON_UNQUOTE(text, '$[*].name' ) AS name FROM TEST;
- 查詢Json字段中所有的值,用 “*”
SELECT id, text -> '$[*].*' AS name FROM TEST;
Mybatis Plus使用LambdaQueryChainWrapper查詢
提示:使用apply方法拼接sql片段,apply 是可以通過占位符的形式,傳入多個參數(shù)。
文章來源:http://www.zghlxwxcb.cn/news/detail-772079.html
例如:文章來源地址http://www.zghlxwxcb.cn/news/detail-772079.html
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());//精確查詢
到了這里,關(guān)于Mybatis-Plus處理Mysql Json類型字段的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!