mybatis反序列化数据库中的json对象为自定义的对象

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

/**
 * Author:daWang
 * Date:2023/8/22  17:20
 */
public class JsonArrayTypeHandler<T> extends BaseTypeHandler<List<T>> {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final Class<T> type;

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

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<T> list, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(i, objectMapper.writeValueAsString(list));
        } catch (JsonProcessingException e) {
            throw new SQLException("Error serializing object to JSON string", e);
        }
    }

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

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

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

    private List<T> parseJson(String json) throws SQLException {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, type));
        } catch (Exception e) {
            throw new SQLException("Error deserializing JSON string to object", e);
        }


    }

}

mapper

	/**
	* javaType 指定反序列化的对象类型
	*/
    @Select("SELECT * xxxx WHERE  hp.house_index_code=#{houseIndexId} ")
    @Results({
            @Result(column = "person_photo", property = "personPhoto", typeHandler = JsonArrayTypeHandler.class,javaType = PersonPhoto.class),
    })
    List<BuildingHouseDetail> selectHouseDetailList(String houseIndexId);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值