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);

你可能感兴趣的:(java,mybatis,数据库,json)