How to Pass Java List of Objects to Oracle Stored Procedure Using MyBatis?

后端 未结 2 641
死守一世寂寞
死守一世寂寞 2020-12-05 08:46

I have been googling this for a while and cannot seem to find any real answers.

I have an Oracle stored procedure that has a number of in parameters that have a type

2条回答
  •  执笔经年
    2020-12-05 09:19

    I can't tell if you do already or not, but you'll need Oracle objects defined.

    CREATE OR REPLACE TYPE SCHEMA."YOUR_OBJECT" AS OBJECT
    (
        field_one    varchar2(50),
        field_two    varchar2(100)
    );
    /
    CREATE OR REPLACE TYPE SCHEMA."YOUR_OBJECT_ARRAY" AS TABLE OF YOUR_OBJECT;
    /
    

    Then you can write type handlers to map the Java objects to the Oracle objects.

    import oracle.sql.ARRAY;
    import oracle.sql.ArrayDescriptor;
    import oracle.sql.STRUCT;
    import oracle.sql.StructDescriptor;
    ....
    public class YourTypeHandler implements TypeHandler
    {
    ....
        public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
        {
            List objects = (List) parameter;
    
            StructDescriptor structDescriptor = StructDescriptor.createDescriptor("YOUR_OBJECT", ps.getConnection());
    
            STRUCT[] structs = new STRUCT[objects.size()];
            for (int index = 0; index < objects.size(); index++)
            {
                YourObject pack = packs.get(index);
                Object[] params = new Object[2];
                params[0] = pack.getFieldOne();
                params[1] = pack.getFieldTwo();
                STRUCT struct = new STRUCT(structDescriptor, ps.getConnection(), params);
                structs[index] = struct;
            }
    
            ArrayDescriptor desc = ArrayDescriptor.createDescriptor("YOUR_OBJECT_ARRAY", ps.getConnection());
            ARRAY oracleArray = new ARRAY(desc, ps.getConnection(), structs);
            ps.setArray(i, oracleArray);
        }
    }
    

    Then invoke the procedure,

    call your_proc
    (
    #{yourObjects, javaType=Object, jdbcType=ARRAY, jdbcTypeName=YOUR_OBJECT_ARRAY, mode=IN, typeHandler=YourObjectArrayTypeHandler}
    )
    

提交回复
热议问题