java MybatisPlus 读取mysql的json字段问题

2023-09-05 16:20:30 浏览数 (1)

解决方案

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

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

如下部分代码:

代码语言:javascript复制
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复制
    @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

查询结果:

0 人点赞