MyBatisPlus使用自定义JsonTypeHandler实现自动转化JSON

个人主页 :金鳞踏雨

个人简介 :大家好,我是金鳞,一个初出茅庐的Java小白

目前状况:22届普通本科毕业生,几经波折了,现在任职于一家国内大型知名日化公司,从事Java开发工作

我的博客:这里是CSDN,是我学习技术,总结知识的地方。希望和各位大佬交流,共同进步 ~

背景

在项目中使用了Mybatis-Plus框架,调用了Mapper层的 insert() ,如下所示,DingRobotMsg对象 的属性包含了其它的对象(Text、Content),数据库表字段里有与之对应的字段,类型为json

java 复制代码
@Service
public class DingRobotMsgServiceImpl extends ServiceImpl<DingRobotMsgMapper, DingRobotMsg> implements IDingRobotMsgService {

    @Autowired
    private DingRobotMsgMapper dingRobotMsgMapper;

    @Override
    public void insertRobotMsg(DingRobotMsg dingRobotMsg) {
        // 新增
        dingRobotMsg.setState("1");
        if (dingRobotMsg.getMsgtype().equals("text") || dingRobotMsg.getMsgtype().equals("file")) {
            dingRobotMsgMapper.insert(dingRobotMsg);
        } else {
            // TODO: 类型错误!
        }
    }
}
java 复制代码
@Data
@TableName("t_dingtalk_recemsg")
public class DingRobotMsg {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField(value = "msgtype")
    private String msgtype;

    private Content content;

    private Text text;

    // ...
}

这种情况,我们如何在不增加业务逻辑(数据处理)的情况下实现数据库的插入操作呢?

JsonTypeHandler

有的对象字段需要存储为Json ,可以直接转成Json赋值后再保存。也可以通过Mybatis的TypeHandler自动处理。

通用 JsonTypeHandler 工具类

java 复制代码
/**
 * 对象字段转存为Json类型
 * @param <T>
 */
@MappedTypes({Text.class, Content.class})
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {

    private final Class<T> type;

    public JsonTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        // 将对象转换为JSON字符串并设置到PreparedStatement中
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从ResultSet中获取JSON字符串并转换为指定类型的对象
        String jsonString = rs.getString(columnName);
        return JSON.parseObject(jsonString, type);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从ResultSet中获取JSON字符串并转换为指定类型的对象
        String jsonString = rs.getString(columnIndex);
        return JSON.parseObject(jsonString, type);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从CallableStatement中获取JSON字符串并转换为指定类型的对象
        String jsonString = cs.getString(columnIndex);
        return JSON.parseObject(jsonString, type);
    }
}

JsonTypeHandler 的使用

在entry对象的字段上面加上下面的注解即可!

java 复制代码
@TableField(typeHandler = JsonTypeHandler.class)
private Content content;

@TableField(typeHandler = JsonTypeHandler.class)
private Text text;

文章到这里就结束了,如果有什么疑问的地方,可以在评论区指出~

希望能和大佬们一起努力,诸君顶峰相见

再次感谢各位小伙伴儿们的支持!!!

相关推荐
叼烟扛炮37 分钟前
[LangChain] 学习笔记(15):为什么你的重试没用——429、抖动、fallback 与熔断
java·服务器·前端
文丑颜不良啊1 小时前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode3421~3440题目解析
java·leetcode
code2cat4 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
码云社区5 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区5 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件6 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水6 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
吃我一窝jio7 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
Resean022310 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存