java mybatis操作 postgresql array数组类型

找了半天没有找到postgresql中关于array数组类型的字段如何对应到java中的数据类型,后来找到了mybatis的TypeHandler,只要实现一个自定义的TypeHandler就行了,如下,我定义了几个基础数据类型的数组


public class ArrayTypeHandler extends BaseTypeHandler {

    private static final String TYPE_NAME_VARCHAR = "varchar";
    private static final String TYPE_NAME_INTEGER = "integer";
    private static final String TYPE_NAME_BOOLEAN = "boolean";
    private static final String TYPE_NAME_NUMERIC = "numeric";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object[] parameter, JdbcType jdbcType) throws SQLException {
        String typeName = null;
        if (parameter instanceof Integer[]) {
            typeName = TYPE_NAME_INTEGER;
        } else if (parameter instanceof String[]) {
            typeName = TYPE_NAME_VARCHAR;
        } else if (parameter instanceof Boolean[]) {
            typeName = TYPE_NAME_BOOLEAN;
        } else if (parameter instanceof Double[]) {
            typeName = TYPE_NAME_NUMERIC;
        }

        if (typeName == null) {
            throw new TypeException("ArrayTypeHandler parameter typeName error, your type is " + parameter.getClass().getName());
        }

        // 3行是关键的代码,创建Array,然后ps.setArray(i, array)就可以了
        Connection conn = ps.getConnection();
        Array array = conn.createArrayOf(typeName, parameter);
        ps.setArray(i, array);

    }

    @Override
    public Object[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getArray(resultSet.getArray(s));
    }

    @Override
    public Object[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getArray(resultSet.getArray(i));
    }

    @Override
    public Object[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getArray(callableStatement.getArray(i));
    }

    private Object[] getArray(Array array) {
        if (array == null) {
            return null;
        }
        try {
            return (Object[]) array.getArray();
        } catch (Exception e) {
        }
        return null;
    }
}

然后在实体类里面对应的字段配置这个转换器就行,如果是配置文件需要在 xxmap.xml中配置对应属性


@ColumnType(typeHandler = com.mvc.typehandler.ArrayTypeHandler.class)
private String[] cities; //所操作的城市code列表,为空表示所有城市
@ColumnType(typeHandler = com.mvc.typehandler.ArrayTypeHandler.class)
private String[] areaTypes; //操作的行业类型code列表,为空表示所有行业
@ColumnType(typeHandler = com.jmtool.mvc.typehandler.ArrayTypeHandler.class)
private Integer[] targetStatus; //操作的目标数据状态





你可能感兴趣的:(java mybatis操作 postgresql array数组类型)