1 首先我已经在oracle 数据库创建了自定义对象Type Object 和 自定义表 Type table 和procedure
以下为相关ddl
create or replace TYPE ASU_SAVE_OBJ AS OBJECT ( ASUCODE VARCHAR2(8 BYTE) , ASU_TITLE VARCHAR2(60 BYTE), GEOGRAPHICAL_DEF VARCHAR2(1000 BYTE), STATECODE VARCHAR2(2 BYTE), PROGYEAR NUMBER(4,0) ); create or replace TYPE T_ASU_SAVE_OBJ AS TABLE OF ASU_SAVE_OBJ; create or replace PROCEDURE ASU_BATCH_SAVE ( list_asu IN T_ASU_SAVE_OBJ ) AS BEGIN for i in list_asu.first .. list_asu.last loop insert into asu (ASUCODE, ASU_TITLE, geographical_def,statecode,progyear) VALUES (list_asu(i).asucode, list_asu(i).ASU_TITLE, list_asu(i).geographical_def, list_asu(i).statecode, list_asu(i).progyear); --dbms_output.put_line(list_asu(i).asucode || list_asu(i).ASU_TITLE || list_asu(i).geographical_def || list_asu(i).statecode || list_asu(i).progyear); end loop; commit; EXCEPTION WHEN OTHERS THEN rollback; END ASU_BATCH_SAVE;
2. 在了解如何 把 java collection 通过jdbc 转为 db array/table(db collection) 之前
首先知道如何把 java object 参数转换为db object
一个db object 需要使用Object[] 来表示, object[] 下的每个元素表示db object 的一个属性
参考上面对应ASU_SAVE_OBJ
java object[] 对应的db object 如下
代码
Object[] bean = new Object[]{asuCode,asuTitle,asuPgd,this.stateCode,Integer.parseInt(progYear)};
然后把java collection 转换为 db collection
代码
private List<Object> convert2DBObj(String asuCode, String stateCode, String progYear, String selCompAreas){ String[] compArr=selCompAreas.split(" "); List<Object> result=new ArrayList<Object>(); for(String compArea: compArr){ if(compArea.startsWith("+")){ logger.debug("List["+ stateCode+","+asuCode+","+progYear+","+compArea+",+]"); result.add(new Object[] {stateCode,asuCode,progYear,compArea.substring(1),"+" }); } else{ logger.debug("List["+ stateCode+","+asuCode+","+progYear+","+compArea+",-]"); result.add(new Object[] {stateCode,asuCode,progYear,compArea.substring(1),"-" }); } } return result; }
3 最后使用JDBC API 通过oracle.array 和 ArrayDescriptor 转换java list 为array
其中我已经在oracle 数据库创建了一个叫ASU_BATCH_SAVE(?) procedure
(1)这里解释一下ArrayDescriptor, ArrayDescriptor 主要用来绑定这个procedure的输入参数类型是T_ASU_SAVE_OBJ, 注意这里我已经在数据库创建了
CREATE OR REPLACE TYPE T_ASU_SAVE_OBJ
AS TABLE OF ASU_SAVE_OBJ; 这样一个输入参数
(2) ARRAY 需要三个参数一个是ArrayDescriptor ,一个是connection,最后一个书list<object> 但是这里必须转换为最终形式Object[] arrayData = listASU.toArray();
因为只接收Object[]
代码:
dataSource = ServiceLocator.getInstance().getDataSource(vProcessMode); dbConnection = DAOUtility.openConnection(dataSource, this.autoCommit); String sql = "{call ASU_BATCH_SAVE(?)} "; cst = dbConnection.prepareCall(sql); Object[] arrayData = listASU.toArray(); ArrayDescriptor descriptor = new ArrayDescriptor("T_ASU_SAVE_OBJ", dbConnection); ARRAY t_list = new ARRAY(descriptor,dbConnection,arrayData); cst.setArray(1, t_list); cst.execute();