1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Mybatis自定义Handler实现Json数组转List对象

Mybatis自定义Handler实现Json数组转List对象

时间:2023-07-27 15:40:43

相关推荐

Mybatis自定义Handler实现Json数组转List对象

先定义一个ListTypeHandler

package com.fiture.marine.utils;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import mons.collections4.CollectionUtils;import mons.lang.StringUtils;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 com.alibaba.fastjson.JSON;import com.alibaba.fastjson.TypeReference;/*** 描述** @author mistra@* @date /6/10*/@MappedJdbcTypes(JdbcType.VARBINARY)@MappedTypes({List.class})public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType)throws SQLException {String content = CollectionUtils.isEmpty(parameter) ? null : JSON.toJSONString(parameter);ps.setString(i, content);}@Overridepublic List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {return this.getListByJsonArrayString(rs.getString(columnName));}@Overridepublic List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return this.getListByJsonArrayString(rs.getString(columnIndex));}@Overridepublic List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return this.getListByJsonArrayString(cs.getString(columnIndex));}private List<T> getListByJsonArrayString(String content) {return StringUtils.isBlank(content) ? new ArrayList<>() : JSON.parseObject(content, this.specificType());}/*** 具体类型,由子类提供** @return 具体类型*/protected abstract TypeReference<List<T>> specificType();}

泛型为需要Json转换为的目标实体对象

package com.fiture.marine.utils;import java.util.List;import com.alibaba.fastjson.TypeReference;import com.fiture.marine.wechat.pojo.dto.AttachmentAddDTO;/*** 描述** @author mistra@* @date /6/10*/public class AttachmentListTypeHandler extends ListTypeHandler<AttachmentAddDTO> {@Overrideprotected TypeReference<List<AttachmentAddDTO>> specificType() {return new TypeReference<List<AttachmentAddDTO>>() {};}}

使用

/*** 扩展字段*/@TableField(value = "attachments", typeHandler = AttachmentListTypeHandler.class)private List<AttachmentAddDTO> attachments;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。