MyBatisPlus自定义JsonTypeHandler实现自动转化JSON问题
作者:金鳞踏雨
这篇文章主要介绍了MyBatisPlus自定义JsonTypeHandler实现自动转化JSON问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
背景
在项目中使用了Mybatis-Plus框架,调用了Mapper层的 insert()
如下所示,DingRobotMsg对象 的属性包含了其它的对象(Text、Content)
数据库表字段里有与之对应的字段,类型为json
@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: 类型错误!
}
}
}@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 工具类
/**
* 对象字段转存为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对象的字段上面加上下面的注解即可!
@TableField(typeHandler = JsonTypeHandler.class) private Content content; @TableField(typeHandler = JsonTypeHandler.class) private Text text;
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
