从存储过程返回的STRUCT中读取ARRAY

时间:2017-03-17 09:24:52

标签: java oracle jdbc

在数据库中有三种Oracle自定义类型(简化),如下所示:

create or replace TYPE T_ENCLOSURE AS OBJECT(
  ENCLOSURE_ID      NUMBER(32,0),
  ENCLOSURE_NAME    VARCHAR2(255 BYTE),
  ANIMALS           T_ARRAY_ANIMALS,

  MEMBER FUNCTION   CHECK_IF_RED RETURN BOOLEAN
);


create or replace TYPE T_ARRAY_ANIMALS is TABLE OF T_ANIMAL;


create or replace TYPE T_ANIMAL AS OBJECT(
  ANIMAL_ID NUMBER(32,0),
  NUMBER_OF_HAIRS NUMBER(32,0)
);

和一个构建对象树的函数

FUNCTION GET_ENCLOSURE ( f_enclosure_id zoo_schema.ENCLOSURE_TABLE.ENCLOSURE_ID%TYPE ) RETURN T_ENCLOSURE
AS
    v_ENC T_ENCLOSURE;
    v_idx pls_integer;

BEGIN

    v_ENC := T_ENCLOSURE(
        f_enclosure_id,
        NULL,
        T_ARRAY_ANIMALS(T_ANIMAL(NULL,NULL))
    );

    SELECT ENCLOSURE_NAME
    INTO   v_ENC.ENCLOSURE_NAME
    FROM   ENCLOSURE_TABLE WHERE ENCLOSURE_ID = f_ENCLOSURE_ID;

    SELECT
        CAST(MULTISET(
            SELECT ANIMAL_ID, NUMBER_OF_HAIRS
            FROM   ANIMAL_TABLE
            WHERE  ENCLOSURE_ID = f_ENCLOSURE_ID
        ) AS T_ARRAY_ANIMALS
    )
    INTO v_ENC.ANIMALS
    FROM dual;

RETURN v_ENC;

END;

现在我想调用GET_ENCLOSURE函数并在我的Java代码中使用其结果T_ENCLOSURE对象。

// prepare the call
Connection connection = MyConnectionFactory.getConnection(SOME_CONNECTION_CONFIG);
CallableStatement stmt = connection.prepareCall("{? = call zoo_schema.zoo_utils.GET_ENCLOSURE( ? )}");
stmt.registerOutParameter(1, OracleTypes.STRUCT, "zoo_schema.T_ENCLOSURE");
stmt.setInt(2, 6);  // fetch data for ENCLOSURE#6

// execute function
stmt.executeQuery();

// extract the result
Struct resultStruct = (Struct)stmt.getObject(1); // java.sql.Struct

我可以通过

访问 ID NAME
Integer id = ((BigInteger)resultStruct.getAttributes()[0]).intValue(); // works for me
String name = (String)resultStruct.getAttributes()[1]); // works for me

然而,我似乎无法获得动物名单

resultStruct.getAttributes()[2].getClass().getCanonicalName(); // oracle.sql.ARRAY
ARRAY arrayAnimals = (ARRAY)jdbcStruct.getAttributes()[2];
arrayAnimals.getArray(); // throws a java.sql.SQLException("Internal Error: Unable to resolve name")

我在这里有一些试验和错误,包括

OracleConnection oracleConnection = connection.unwrap(OracleConnection.class);
STRUCT resultOracleStruct = (STRUCT) stmt.getObject(1); // oracle.sql.STRUCT
oracleConnection.createARRAY("zoo_schema.T_ARRAY_ANIMALS", resultOracleStruct.getAttributes()[2]) // throws an SQLException("Fail to convert to internal representation: oracle.sql.ARRAY@8de7cfc4")

但也没有运气。

如何将动物列表变为List<TAnimal>

4 个答案:

答案 0 :(得分:1)

创建实现java.sql.SQLData的对象。在此方案中,创建TEnclosureTAnimal类,这两个类都实现SQLData

仅供参考,在较新的Oracle JDBC版本中,不推荐使用oracle.sql.ARRAY等类型,而使用java.sql类型。虽然我不确定如何仅使用java.sql API编写数组(如下所述)。

实施readSQL()时,您需要按顺序阅读字段。您获得java.sql.Array sqlInput.readArray()。所以TEnclosure.readSQL()看起来像这样。

@Override
public void readSQL(SQLInput sqlInput, String s) throws SQLException {
    id = sqlInput.readBigDecimal();
    name = sqlInput.readString();
    Array animals = sqlInput.readArray();
    // what to do here...
}

注意:readInt()也存在,但Oracle JDBC似乎始终为BigDecimal提供NUMBER

您会注意到某些API(例如java.sql.Array)具有采用类型映射的方法Map<String, Class<?>>这是Oracle类型名称到其实现SQLData的相应Java类的映射({{ 1}}也可以工作吗?)。

如果您只是致电ORAData,除非JDBC驱动程序通过Array.getArray()了解您的类型映射,否则您将获得Struct个对象。但是,在连接上设置typeMap并不适合我,所以我使用Connection.setTypeMap(typeMap)

在某处创建getArray(typeMap)并为您的类型添加条目:

Map<String, Class<?>> typeMap

typeMap.put("T_ENCLOSURE", TEnclosure.class); typeMap.put("T_ANIMAL", TAnimal.class); 实施中,请致电SQLData.readSQL(),该sqlInput.readArray().getArray(typeMap)会在Object[]条目或Object类型中返回TAnimal

当然,转换为List<TAnimal>的代码变得乏味,所以只需使用此实用程序函数并根据您的需要进行调整,直至null与空列表策略:

/**
 * Constructs a list from the given SQL Array
 * Note: this needs to be static because it's called from SQLData classes.
 *
 * @param <T> SQLData implementing class
 * @param array Array containing objects of type T
 * @param typeClass Class reference used to cast T type
 * @return List<T> (empty if array=null)
 * @throws SQLException
 */
public static <T> List<T> listFromArray(Array array, Class<T> typeClass) throws SQLException {
    if (array == null) {
        return Collections.emptyList();
    }
    // Java does not allow casting Object[] to T[]
    final Object[] objectArray = (Object[]) array.getArray(getTypeMap());
    List<T> list = new ArrayList<>(objectArray.length);
    for (Object o : objectArray) {
        list.add(typeClass.cast(o));
    }
    return list;
}

编写数组

弄清楚如何编写阵列令人沮丧,Oracle API需要一个Connection才能创建一个数组,但是在writeSQL(SQLOutput sqlOutput)的上下文中你没有明显的连接。幸运的是,this blog有一个技巧/黑客来获取我在这里使用的OracleConnection

使用createOracleArray()创建数组时,为类型名称指定列表类型T_ARRAY_ANIMALS),而不是单数对象类型。

这是编写数组的通用函数。在您的情况下,listType"T_ARRAY_ANIMALS",您可以传入List<TAnimal>

/**
 * Write the list out as an Array
 *
 * @param sqlOutput SQLOutput to write array to
 * @param listType array type name (table of type)
 * @param list List of objects to write as an array
 * @param <T> Class implementing SQLData that corresponds to the type listType is a list of.
 * @throws SQLException
 * @throws ClassCastException if SQLOutput is not an OracleSQLOutput
 */
public static <T> void writeArrayFromList(SQLOutput sqlOutput, String listType, @Nullable List<T> list) throws SQLException {
    final OracleSQLOutput out = (OracleSQLOutput) sqlOutput;
    OracleConnection conn = (OracleConnection) out.getSTRUCT().getJavaSqlConnection();
    conn.setTypeMap(getTypeMap());  // not needed?
    if (list == null) {
        list = Collections.emptyList();
    }
    final Array array = conn.createOracleArray(listType, list.toArray());
    out.writeArray(array);
}

注意:

  • 有一次我认为setTypeMap是必需的,但现在当我删除该行时,我的代码仍然有用,所以我不确定是否有必要。
  • 我不确定你是应该写null还是空数组,但我认为空数组更正确。

有关Oracle类型的提示

  • Oracle将所有内容都大写,因此所有类型名称都应为大写。
  • 如果您的默认架构中没有类型,则可能需要指定SCHEMA.TYPE_NAME
  • 如果您所连接的用户不是所有者,请记住grant execute类型 如果您对包执行了但不是类型,getArray()在尝试查找类型元数据时会抛出异常。

<强>弹簧

对于使用 Spring 的开发人员,您可能需要查看提供SqlArrayValueSqlReturnArray的{​​{3}},这对于创建{{1}非常有用对于将数组作为参数或返回数组的过程。

Spring Data JDBC Extensions章解释了如何使用数组参数调用过程。

答案 1 :(得分:0)

只要Oracle特定的解决方案足够,关键在于DTO。所有这些都必须实施ORADataORADataFactory

public class TAnimal implements ORAData, ORADataFactory {
    Integer animal_id, number_of_hairs;

    public TAnimal() { }

    // [ Getter and Setter omitted here ]

    @Override
    public Datum toDatum(Connection connection) throws SQLException {
        OracleConnection oracleConnection = connection.unwrap(OracleConnection.class);
        StructDescriptor structDescriptor = StructDescriptor.createDescriptor("zoo_schema.T_ANIMAL", oracleConnection);
        Object[] attributes = {
                this.animal_id,
                this.number_of_hairs
        };
        return new STRUCT(structDescriptor, oracleConnection, attributes);
    }

    @Override
    public TAnimal create(Datum datum, int sqlTypeCode) throws SQLException {
        if (datum == null) {
            return null;
        }
        Datum[] attributes = ((STRUCT) datum).getOracleAttributes();
        TAnimal result = new TAnimal();
        result.animal_id = asInteger(attributes[0]); // see TEnclosure#asInteger(Datum)
        result.number_of_hairs = asInteger(attributes[1]); // see TEnclosure#asInteger(Datum)
        return result;
    }

}

public class TEnclosure implements ORAData, ORADataFactory {

    Integer enclosureId;
    String enclosureName;
    List<Animal> animals;

    public TEnclosure() {
        this.animals = new ArrayList<>();
    }

    // [ Getter and Setter omitted here ]

    @Override
    public Datum toDatum(Connection connection) throws SQLException {
        OracleConnection oracleConnection = connection.unwrap(OracleConnection.class);
        StructDescriptor structDescriptor = StructDescriptor.createDescriptor("zoo_schema.T_ENCLOSURE", oracleConnection);
        Object[] attributes = {
                this.enclosureId,
                this.enclosureName,
                null // TODO: solve this; however, retrieving data works without this
        };
        return new STRUCT(structDescriptor, oracleConnection, attributes);
    }

    @Override
    public TEnclosure create(Datum datum, int sqlTypeCode) throws SQLException {
        if (datum == null) {
            return null;
        }
        Datum[] attributes = ((STRUCT) datum).getOracleAttributes();
        TEnclosure result = new TEnclosure();
        result.enclosureId = asInteger(attributes[0]);
        result.enclosureName = asString(attributes[1]);
        result.animals = asListOfAnimals(attributes[2]);
        return result;
    }

    // Utility methods

    Integer asInteger(Datum datum) throws SQLException {
        if (datum == null)
            return null;
        else
            return ((NUMBER) datum).intValue(); // oracle.sql.NUMBER
    }

    String asString(Datum datum) throws SQLException {
        if (datum = null)
            return null;
        else
            return ((CHAR) datum).getString(); // oracle.sql.CHAR
    }

    List<TAnimal> asListOfAnimals(Datum datum) throws SQLException {
        if (datum == null)
            return null;
        else {
            TAnimal factory = new TAnimal();

            List<TAnimal> result = new ArrayList<>();

            ARRAY array = (ARRAY) datum; // oracle.sql.ARRAY
            Datum[] elements = array.getOracleArray();
            for (int i = 0; i < elements.length; i++) {
                result.add(factory.create(elements[i], 0));
            }
            return result;
        }
    }
}

然后获取数据就像这样:

    TEnclosure factory = new TEnclosure();

    Connection connection = null;
    OracleConnection oracleConnection = null;
    OracleCallableStatement oracleCallableStatement = null;

    try {
        connection = MyConnectionFactory.getConnection(SOME_CONNECTION_CONFIG);
        oracleConnection = connection.unwrap(OracleConnection.class);
        oracleCallableStatement = (OracleCallableStatement) oracleConnection.prepareCall("{? = call zoo_schema.zoo_utils.GET_ENCLOSURE( ? )}");

        oracleCallableStatement.registerOutParameter(1, OracleTypes.STRUCT, "zoo_schema.T_ENCLOSURE");
        oracleCallableStatement.setInt(2, 6);  // fetch data for ENCLOSURE#6

        // Execute query
        oracleCallableStatement.executeQuery();

        // Check result
        Object oraData = oracleCallableStatement.getORAData(1, factory);
        LOGGER.info("oraData is a {}", oraData.getClass().getName()); // acme.zoo.TEnclosure

    } finally {
        ResourceUtils.closeQuietly(oracleCallableStatement);
        ResourceUtils.closeQuietly(oracleConnection);
        ResourceUtils.closeQuietly(connection); // probably not necessary...
    }

答案 2 :(得分:0)

您可能会这样转换为router.get("/api/sse/register/*", async (ctx: Router.IRouterContext) => { const i = ctx.path.lastIndexOf("/"); const asset: string = ctx.path.slice(18, i); const orgId: string = ctx.path.slice(i + 1); let assetObj: any = myCache.get(asset); // setting headers to specify event stream connection ctx.set({ "Access-Control-Allow-Origin" : "*", "Content-Type" : "text/event-stream; charset=utf-8", "Cache-Control" : "no-cache", "Connection" : "Keep-Alive", "Transfer-encoding": "identity", }); ctx.status = 200; ctx.flushHeaders(); /* Creating pass through stream that simply pipes input given to it to its assigned output stream which in this case is ctx.body*/ const stream = new PassThrough(); ctx.body = stream; // saving mapping between orgId and its stream object to push data to assetObj[orgId] = stream; myCache.set(asset, assetObj); sendHeartbeatSignal(orgId, asset, assetObj); }

const source = new EventSource("/api/sse/register/trailers/" + org.id);
source.addEventListener("message", (event: any) => this.onUpdate(this, event));

答案 3 :(得分:0)

我只分享对我有用的逻辑。您可以尝试从PL / SQL到Java检索ARRAY响应。

CallableStatement callstmt = jdbcConnection.prepareCall("{call PROCEDURE_NAME(?, ?)}");
callstmt.setArray(1, array);
callstmt.registerOutParameter(2,Types.ARRAY, <ARRAY_NAME_DECLARED_IN_PL/SQL>);
// Do all execute operations
    Array arr = callstmt.getArray(1);
            if (arr != null) {
               Object[] data = (Object[]) arr.getArray();
               for (Object a : data) {
                   OracleStruct empstruct = (OracleStruct) a;
                   Object[] objarr = empstruct.getAttributes();
                   <Your_Pojo_class> r = new <Your_Pojo_class>(objarr[0].toString(), objarr[1].toString());
                   System.out.println("Response-> : "+ r.toString());
               }
            }