mybatis typehandler适配postgresql中的point数组数据类型

mybatis typehandler适配postgresql中的point数组数据类型


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.postgresql.geometric.PGpoint;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TypeHandlePGpointArray extends BaseTypeHandler<PGpoint[]> {
    private static final String TYPE_NAME = "point";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PGpoint[] parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.length == 0) {
            Connection conn = ps.getConnection();
            Array array = conn.createArrayOf(TYPE_NAME, new PGpoint[0]);
            ps.setArray(i, array);
            array.free();
            return;
        }
        Array arrayOf = ps.getConnection().createArrayOf(TYPE_NAME, parameter);
        log.debug("class#=" + arrayOf.getArray().getClass());
        ps.setArray(i, arrayOf);
        arrayOf.free();
    }

    @Override
    public PGpoint[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getPGpoints(rs.getArray(columnName));
    }

    @Override
    public PGpoint[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getPGpoints(rs.getArray(columnIndex));
    }

    @Override
    public PGpoint[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getPGpoints(cs.getArray(columnIndex));
    }

    private PGpoint[] getPGpoints(Array array2) throws SQLException {
        Array array = array2;
        if (array == null) {
            return new PGpoint[0];
        }
        if (array.getArray() == null) {
            return new PGpoint[0];
        }
        Object[] data = (Object[]) array.getArray();
        List<PGpoint> list = new ArrayList<>();
        for (Object it : data) {
            list.add((PGpoint) it);
        }
        return list.toArray(PGpoint[]::new);
    }
}

posted @ 2022-10-25 15:48  Ronald Hu  阅读(371)  评论(0编辑  收藏  举报