首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >java MybatisPlus 读取mysql的json字段问题

java MybatisPlus 读取mysql的json字段问题

作者头像
躺平程序员老修
发布2023-09-05 16:20:30
发布2023-09-05 16:20:30
1.8K00
代码可运行
举报
运行总次数:0
代码可运行

解决方案

当数据库使用json类型字段时,mybatisPlus如何对应类型,可以直接查出数据:

  • 添加 @TableName(autoResultMap = true)
  • 字段添加 @TableField(typeHandler = FastjsonTypeHandler.class)
  • 字段类型使用json 如 com.alibaba.fastjson.JSONObject

如下部分代码:

代码语言:javascript
代码运行次数:0
运行
复制
package com.central.street.entity;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;


@Data
@TableName(value = "manuscript", autoResultMap = true)    // autoResultMap 
public class Manuscript implements Serializable {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
   
    @TableField(typeHandler = FastjsonTypeHandler.class)   // typeHandler 
    private JSONObject coverContent;                       // JSONObject
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime topAt;
}

查询构造器 QueryWrapper 使用示例

  • 查询固定字段、条件 wrapper.select()
代码语言:javascript
代码运行次数:0
运行
复制
    @Override
    @Cached(name="manuscript:list:organizationId:",key = "#organizationId+'-'+#pageNum+'-'+#pageSize",
            expire = 300,cacheNullValue=true)
    @CacheRefresh(refresh = 60, stopRefreshAfterLastAccess = 300)
    public Page<Manuscript> getList(long organizationId, int pageNum, int pageSize) {
        QueryWrapper<Manuscript> wrapper = new QueryWrapper<>();
        // Manuscript.class中所有字段,除了'content'
        wrapper.select(Manuscript.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("content")).
                isNull("deleted_time").
                eq("organization_id",organizationId).
                orderByDesc("top_at").
                orderByDesc("created_time");


        Page<Manuscript> manuscriptPage =  page(new Page<>(pageNum, pageSize), wrapper);

        /* 迭代处理数据
        List<Manuscript> records = manuscriptPage.getRecords();
        Iterator iterator = records.iterator();
        while(iterator.hasNext()) {
            Manuscript manuscript = (Manuscript) iterator.next();
            manuscript.setTitle("迭代修改引用数据");
        }
        */

        return manuscriptPage;
    }

模型方式

https://www.jianshu.com/p/ceb1df475021

查询结果:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解决方案
  • 查询构造器 QueryWrapper 使用示例
  • 模型方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档