1

我正在尝试将 Java 数组传递给 PLSQL 存储过程,但是当我尝试执行时,出现以下异常

java.sql.SQLException: Inconsistent java and sql object types

我的 DAO 类代码片段

List projectList = new ArrayList();

public void saveRecord(List<Project> project) 
                       throws DatabaseException,SQLException {

    for (Project items: project) {
        insertRecord(items);
    }
}

private void insertRecord(Project project) throws SQLException {
    projectList.add(project);

callablestatement = 
         (OracleCallableStatement)connection.prepareCall("{call my_proc(?)}");

Object[] project1 = projectList.toArray();

StructDescriptor projectTypeDesc = StructDescriptor.createDescriptor("MY_TYPE",
conn);

STRUCT structProject1 = new STRUCT(projectTypeDesc, 
connection, project);

STRUCT[] structArrayOfProjects = {structProject1};

 ArrayDescriptor projectTypeArrayDesc = ArrayDescriptor.createDescriptor
("MY_ARRAY", connection); 

ARRAY arrayOfProjects = new ARRAY(projectTypeArrayDesc, connection,
structArrayOfProjects);// error in this line

callablestatement.setArray(1, arrayOfProjects);  

我该如何解决这个问题?

编辑 1

如果我这样做

Object[] project1 = new Object[]{project.getProjectId(), project.getProjectTitle()};

然后没有错误和记录被插入到表中。

但是,如果我这样做

Object[] project1 = projectList.toArray();

然后抛出异常Inconsistent java and sql object types

4

1 回答 1

4

正如我在另一个线程中已经说过的,您必须将 object 的字段分配给Project数组Object,同时分配整个Project对象数组。你可以做你想做的事,但是,正如我在另一个线程中已经说过的,你必须遍历项目列表并为列表中的STRUCT每个元素创建一个对象,保存每个项目的字段:

StructDescriptor projectTypeDesc = StructDescriptor.createDescriptor("MY_TYPE",
connection);

// array holding structs, where each struct is based on an array
//   with fields of Project object
STRUCT[] projectsAsStructs = new STRUCT[projectList.size()];

// for each Project object, create a STRUCT object containing its fields
for (int i = 0; i < projectList.size(); ++i) {
  Project project = projectList.get(i);

  Object[] projectFields = new Object[] {project.getProjectId(),
                                         project.getProjectTitle()};

  STRUCT projectStruct = new STRUCT(projectTypeDesc,
                                    connection, projectFields);

  projectsAsStructs[i] = projectStruct;
}

// now you have all your Project objects ready to be saved in one go:
ArrayDescriptor projectTypeArrayDesc = ArrayDescriptor.createDescriptor
("MY_ARRAY", connection); 

ARRAY arrayOfProjects = new ARRAY(projectTypeArrayDesc, connection,
                                  projectsAsStructs);

callablestatement.setArray(1, arrayOfProjects);
于 2013-11-11T07:48:02.827 回答