Mybatis-Plus处理Mysql Json类型字段
MyBatis-Plus 本身不直接支持 MySQL 的 JSON 类型字段,但你可以通过自定义类型处理器(TypeHandler)来实现。
以下是一个简单的例子,演示如何为 MySQL 的 JSON 类型字段创建一个自定义类型处理器:
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.parsers.IbatisSqlSessionFactoryBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.sql.*;
@Mapper
public interface YourEntityMapper extends BaseMapper<YourEntity> {
// Your mapper methods here
}
@Component
public class JsonTypeHandler<T> extends BaseTypeHandler<T> {
private static final ObjectMapper objectMapper = new ObjectMapper();
private 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 {
ps.setString(i, toJSON(parameter));
}
@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return toObject(rs.getString(columnName), type);
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return toObject(rs.getString(columnIndex), type);
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return toObject(cs.getString(columnIndex), type);
}
private String toJSON(T object) {
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private T toObject(String json, Class<T> clazz) {
if (json == null || json.length() == 0) {
评论已关闭