软件编程
位置:首页>> 软件编程>> java编程>> MybatisPlus如何自定义TypeHandler映射JSON类型为List

MybatisPlus如何自定义TypeHandler映射JSON类型为List

作者:回忆里的味道.  发布时间:2023-08-08 14:05:38 

标签:MybatisPlus,TypeHandler,映射,JSON,List

自定义TypeHandler映射JSON类型为List

1. 实体类

这里只展示需要映射的字段,分别在所需映射的字段和实体类上添加注解。 

@Data
@TableName(value = "report", autoResultMap = true)
public class Report {
   private static final long serialVersionUID = 1L;
   @ApiModelProperty("id")
   @TableId(value = "id", type = IdType.AUTO)
   private Integer id;

@ApiModelProperty("报名信息")
   @TableField(typeHandler = ReportUserListTypeHandler.class)
   private List<ReportUser> reportInfo;
}

2. ListTypeHandler

提供一个 JSONArray 转换为 Java List集合的处理器

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

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

@MappedJdbcTypes(JdbcType.VARBINARY)
@MappedTypes({List.class})
public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {

@Override
   public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
       String content = CollUtil.isEmpty(parameter) ? null : JSON.toJSONString(parameter);
       ps.setString(i, content);
   }

@Override
   public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
       return this.getListByJsonArrayString(rs.getString(columnName));
   }

@Override
   public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
       return this.getListByJsonArrayString(rs.getString(columnIndex));
   }

@Override
   public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
       return this.getListByJsonArrayString(cs.getString(columnIndex));
   }

private List<T> getListByJsonArrayString(String content) {
       return StrUtil.isBlank(content) ? new ArrayList<>() : JSON.parseObject(content, this.specificType());
   }

/**
    * 具体类型,由子类提供
    *
    * @return 具体类型
    */
   protected abstract TypeReference<List<T>> specificType();  
}

3. ReportUserListTypeHandler

由具体的子类提供List集合泛型类型

import com.alibaba.fastjson.TypeReference;
import com.hanku.business.model.ReportUser;
import java.util.List;  

public class ReportUserListTypeHandler extends ListTypeHandler<ReportUser> {
   @Override
   protected TypeReference<List<ReportUser>> specificType() {
       return new TypeReference<List<ReportUser>>() {
       };
   }    
}

4. Java 泛型

如果在 ListTypeHandler 类中直接提供 TypeReference<List<T>> 这种类型,那就等效于TypeReference<List<Object>> 这种类型,后续 fastjson 在转换时无法确定具体的 Java 类型,转换后的类型最终就会是 List<JSONObject> ;同理,如果使用 Jackson 作为 JSON 转换工具,不确定具体类型时,最总会被转换为LinkedHashMap 类型,都需要再使用 TypeReference 来转换一次。 

自定义TypeHandler的使用笔记

可通过自定义的TypeHandler实现某个属性在插入数据库以及查询时的自动转换,本例中是要将Map类型的属性转化成CLOB,然后存入数据库。由于是复杂的Map,mp自带的json转换器会丢失部分信息。

类型转换器还可以通过注解配置 java类型和jdbc类型

  • @MappedTypes:注解配置 java 类型

  • @MappedJdbcTypes:注解配置 jdbc 类型

定义

@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class WeightListTypeHandler  extends AbstractJsonTypeHandler<Object> {
    private static Gson gson = new Gson();
    private final Class<?> type;
    public WeightListTypeHandler(Class<?> type) {
        if (log.isTraceEnabled()) {
            log.trace("WeightListTypeHandler(" + type + ")");
        }
        Assert.notNull(type, "Type argument cannot be null");
        this.type = type;
    }
    @Override
    protected Object parse(String json) {
        Type type1 = new TypeToken<Map<String, List<WeightItem>>>(){}.getType();
        return gson.fromJson(json, type1);
    }
    @Override
    protected String toJson(Object obj) {
        return gson.toJson(obj);
    }
    public static void setGson(Gson gson) {
        Assert.notNull(gson, "Gson should not be null");
        WeightListTypeHandler.gson = gson;
    }
}

使用

注意@TableName 注解 autoResultMap 属性

@Data
@NoArgsConstructor
@TableName(value = "mix_target",autoResultMap = true)
public class MixTarget extends Model<MixTarget> {
   @TableId(value = "id", type = IdType.AUTO)
   private Long id;
   /**
    *指标描述
    */
   @TableField("description")
   private String description;
   /**
    * 指标名
    */
   @TableField("name")
   private String name;
   /**
    * 对应属性名
    */
   @TableField("property_name")
   private String propertyName;
   /**
    * 起始点类型
    */
   @TableField("source_type")
   private String sourceType;
   /**
    * 属性对应权值列表
    * key 属性名 value指定条件下的权值
    */
   @TableField(value = "weight_list",typeHandler = WeightListTypeHandler.class,jdbcType = JdbcType.CLOB)
   private Map<String, List<WeightItem>> weightList;
   /**
    * 运行状态
    * 0 新建未运行
    * 1 运行中
    * 2 已运行 成功
    * 3 已运行 失败
    */
   @TableField("status")
   private Integer status;
   /**
    * 是否可用
    * 1 true
    * 0 false
    */
   @TableField("enable")
   private Integer enable;
   @TableField("create_time")
   private LocalDateTime createTime;
}

来源:https://blog.csdn.net/li18215100977/article/details/121267367

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com