Springboot+PostgreSQL+MybatisPlus存储JSON或List、数组(Array)数据

项目架构

Springboot+PostgreSQL+MybatisPlus

从Mongodb转过来的项目,有存储json数据的需求,但是在mybatis-plus上会出点问题

报错: Error updating database. Cause: org.postgresql.util.PSQLException 字段 "" 的类型为 jsonb, 但表达式的类型为 character varying 建议:你需要重写或转换表达式

实体类定义:

java 复制代码
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("tb_user_role")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class TbUserRole extends BaseEntity {

    @TableField("user_id")
    String userId;

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    List<String> roles; // 存储为 JSONB

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    List<String> permissions; // 存储为 JSONB
}

SQL

sql 复制代码
CREATE TABLE tb_user_role (
    id VARCHAR(255) PRIMARY KEY, -- 主键ID,继承自 BaseEntity
    user_id VARCHAR(255) NOT NULL, -- 用户ID
    roles JSONB, -- 角色,存储为 JSONB 类型
    permissions JSONB, -- 权限,存储为 JSONB 类型
    deleted BOOLEAN DEFAULT FALSE, -- 逻辑删除标识
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- 创建时间
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- 更新时间
);

前端传入的结构

java 复制代码
     @Schema(description = "角色,传入的对象需要从Role接口获取")
    List<String> roles;

    @Schema(description = "权限,传入的对象需要从Permission接口获取")
    List<String> permissions;

存储时的问题

复制代码
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1c1e6475]
2024-09-27 17:48:43.398 ERROR [tid] [sid] [pid] [nio-8050-exec-1] c.s.w.h.GlobalExceptionHandler@viewExceptionHandler:66 : 
### Error updating database.  Cause: org.postgresql.util.PSQLException: 错误: 字段 "roles" 的类型为 jsonb, 但表达式的类型为 character varying
  建议:你需要重写或转换表达式
  位置:117
### The error may exist in com/sgcchg/data/mapper/UserRoleMapper.java (best guess)
### The error may involve com.sgcchg.data.mapper.UserRoleMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO tb_user_role  ( id, user_id, roles, permissions, deleted, create_time, update_time )  VALUES (  ?, ?, ?, ?, ?, ?, ?  )
### Cause: org.postgresql.util.PSQLException: 错误: 字段 "roles" 的类型为 jsonb, 但表达式的类型为 character varying
  建议:你需要重写或转换表达式
  位置:117
; bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: 错误: 字段 "roles" 的类型为 jsonb, 但表达式的类型为 character varying
  建议:你需要重写或转换表达式
  位置:117 location: com.sgcchg.business.impl.user.UserServiceImpl:101

问题解决

修改Entity定义

java 复制代码
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("tb_user_role")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class TbUserRole extends BaseEntity {

    @TableField("user_id")
    String userId;

    @TableField(typeHandler = ListToStringTypeHandler.class)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    List<String> roles; // 存储为 JSONB

    @TableField(typeHandler = ListToStringTypeHandler.class)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    List<String> permissions; // 存储为 JSONB
}

添加TypeHandler

java 复制代码
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class ListToStringTypeHandler extends BaseTypeHandler<List<String>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

//    @Override
//    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
//        // 将 List 转为 JSON 字符串存储
//        try {
//            ps.setString(i, objectMapper.writeValueAsString(parameter));
//        } catch (JsonProcessingException e) {
//            throw new SQLException("Could not convert list to JSON", e);
//        }
//    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonString = objectMapper.writeValueAsString(parameter);
            ps.setObject(i, jsonString, JdbcType.OTHER.TYPE_CODE); // 使用 JDBC 的 OTHER 类型插入 JSONB
        } catch (JsonProcessingException e) {
            throw new SQLException("Could not convert list to JSON", e);
        }
    }


    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJsonToList(json);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJsonToList(json);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJsonToList(json);
    }

    private List<String> parseJsonToList(String json) {
        if (json == null || json.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            return objectMapper.readValue(json, List.class);
        } catch (JsonProcessingException e) {
            return Collections.emptyList();
        }
    }


}

保存数据

之后即可保存数据

在数据库中可看到:

相关推荐
xuxie134 小时前
SpringBoot文件下载(多文件以zip形式,单文件格式不变)
java·spring boot·后端
LiRuiJie6 小时前
深入剖析Spring Boot / Spring 应用中可自定义的扩展点
java·spring boot·spring
尚学教辅学习资料8 小时前
Ruoyi-vue-plus-5.x第五篇Spring框架核心技术:5.1 Spring Boot自动配置
vue.js·spring boot·spring
晚安里8 小时前
Spring 框架(IoC、AOP、Spring Boot) 的必会知识点汇总
java·spring boot·spring
上官浩仁9 小时前
springboot ioc 控制反转入门与实战
java·spring boot·spring
叫我阿柒啊9 小时前
从Java全栈到前端框架:一位程序员的实战之路
java·spring boot·微服务·消息队列·vue3·前端开发·后端开发
中国胖子风清扬10 小时前
Rust 序列化技术全解析:从基础到实战
开发语言·c++·spring boot·vscode·后端·中间件·rust
微笑伴你而行11 小时前
目标检测如何将同时有方形框和旋转框的json/xml标注转为txt格式
xml·目标检测·json
cdcdhj12 小时前
数据库存储大量的json文件怎么样高效的读取和分页,利用文件缓存办法不占用内存
缓存·node.js·json
JosieBook14 小时前
【SpringBoot】21-Spring Boot中Web页面抽取公共页面的完整实践
前端·spring boot·python