Mybatis-Plus读写Mysql的Json字段的操作代码
时间:2022-12-13 09:29:43|栏目:JAVA代码|点击: 次
前置条件
确保mysql的版本是5.7+
一、新建mysql表增加json字段
二、pojo类
package com.cxstar.domain; import com.alibaba.fastjson.JSONObject; 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 java.io.Serializable; import java.util.Date; @lombok.Data @TableName(autoResultMap = true) public class Data implements Serializable { @TableId(value = "id",type = IdType.AUTO) private Integer id; // 部分字段省略------------- private String title; private String author; private String publisher; // ----------------------- @TableField(typeHandler = FastjsonTypeHandler.class) private JSONObject aggJson; }
三、测试类
package com.cxstar; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.cxstar.domain.Data; import com.cxstar.domain.SearchMsg; import com.cxstar.mapper.DataMapper; import com.cxstar.service.OrderService; import com.cxstar.service.spider.impl.*; import com.cxstar.service.utils.ExecutorThread; import com.cxstar.service.utils.SpiderThread; import com.cxstar.service.utils.SynContainer; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.ArrayList; import java.util.Date; import java.util.UUID; @SpringBootTest class OrderApplicationTests { @Autowired DataMapper dataMapper; @Test void testJson() { // insert ----------------------------------- Data data = new Data(); data.setTitle("计算机安全技术与方法"); data.setPublisher("<<计算机技术>>编辑部出版"); JSONObject jb = new JSONObject(); jb.put("searchKey", "英格"); jb.put("curPage", "1"); JSONArray js = new JSONArray(); js.add("西北政法大学"); js.add("西安理工大学"); jb.put("source", js); data.setAggJson(jb); dataMapper.insert(data); // ------------------------------------------ // select -------------------------------------- Data data1 = dataMapper.selectById(5837); JSONObject jb2 = data1.getAggJson(); System.out.println(jb2.getJSONArray("source")); // --------------------------------------------- // group by ----------------------------------------------- LambdaQueryWrapper<Data> lqw = new LambdaQueryWrapper<>(); lqw.select(Data::getAggJson); lqw.groupBy(Data::getAggJson); List<Data> dataList = dataMapper.selectList(lqw); System.out.println(dataList); // -------------------------------------------------------- } }
栏 目:JAVA代码
下一篇:Java try-catch-finally异常处理机制详解
本文标题:Mybatis-Plus读写Mysql的Json字段的操作代码
本文地址:http://www.codeinn.net/misctech/221232.html