簡體   English   中英

從存儲過程返回的 STRUCT 中讀取 ARRAY

[英]Read an ARRAY from a STRUCT returned by a stored procedure

數據庫中是三種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

我可以通過以下方式訪問IDNAME

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>

只要特定於 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...
    }

創建實現java.sql.SQLData對象。 在這種情況下,創建TEnclosureTAnimal類,它們都實現SQLData

僅供參考,在較新的 Oracle JDBC 版本中,不推薦使用諸如oracle.sql.ARRAY之類的類型以支持java.sql類型。 盡管我不確定如何僅使用java.sql API 編寫數組(如下所述)。

當您實現readSQL()您會按順序讀取字段。 您使用sqlInput.readArray()獲得java.sql.Array 所以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 似乎總是為NUMBER提供BigDecimal

您會注意到某些 API(例如java.sql.Array具有采用類型映射Map<String, Class<?>>這是 Oracle 類型名稱到實現SQLData的相應 Java 類的映射( ORAData也可以工作? )。

如果您只是調用Array.getArray() ,您將獲得Struct對象,除非 JDBC 驅動程序通過Connection.setTypeMap(typeMap)知道您的類型映射。 但是,在連接上設置 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)的上下文中沒有明顯的 Connection 。 幸運的是, 這個博客有一個技巧/技巧來獲取我在這里使用的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 的開發人員,您可能需要查看Spring Data JDBC Extensions ,它提供了SqlArrayValueSqlReturnArray ,它們對於為將數組作為參數或返回數組的過程創建SimpleJdbcCall非常有用。

7.2.1使用 SqlArrayValue 為 IN 參數設置 ARRAY 值解釋了如何使用數組參數調用過程。

您可能會像這樣轉換為java.sql.Array

Object array = ( (Array) resultOracleStruct.getAttributes()[2]) ).getArray();

我只是分享對我有用的邏輯。 您可以嘗試將 ARRAY 響應從 PL/SQL 檢索到 Java。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM