2011-11-24 6 views
2

단일 행을 삽입하도록 설계된 저장 프로 시저가 있습니다. 나는 방법 다음 (간체 예)에서 최대 절전 모드로에서 작동 :저장 프로 시저를 사용하는 최대 절전 모드 일괄

public void store(int param1, int param2) { 
    Connection con = session.connection(); // obtain JDBC connection from Session object 
    CallableStatement stmt = con.prepareCall("{ call changesalary(?,?) }"); 
    stmt.setInt(1, param1); // first parameter index start with 1 
    stmt.setInt(2, param2); // second parameter 
    stmt.execute(); // call stored procedure 
    cleanup(con, stmt); 
} 

가 (그렇게하지를 수정할 필요없이 더 배치-모두 방법이 저장 프로 시저를 재사용 할 수 있습니다 궁금 새로운 저장 프로 시저를 추가하거나 기존 저장 프로 시저를 수정할 가능성이 있음). 나는이 작업을 수행 할 :

public void batchStore(int[] params1, int[] params2) { 
    for (int i = 0; i < params1.length; i++) { 
     store(params1[i], params2[i]); 
    } 
} 

public void store(int param1, int param2) { 
    Connection con = session.connection(); 
    CallableStatement stmt = con.prepareCall("{ call changesalary(?,?) }"); 
    stmt.setInt(1, param1); 
    stmt.setInt(2, param2); 
    stmt.execute(); 
    cleanup(con, stmt); 
} 

그러나 DB 호출의 많은 양을 방지하기 위해, 나는 오히려 제표 세트를 준비하고 싶은 하나 호출 데이터베이스에 그때 배치 :

public void store(int[] params1, int[] params2) { 
    Connection con = session.connection(); 
    CallableStatement[] stmts = new CallableStatements[params.size]; 

    for (int i = 0; i < params1.length; i++) { 
     CallableStatement stmt = con.prepareCall("{ call changesalary(?,?) }"); 
     stmt.setInt(1, params1[i]); 
     stmt.setInt(2, params2[i]); 
     stmts[i] = stmt; 
    } 

    con.executeStatements(stmts); 
} 

위의 의사 코드를 달성 할 수 있습니까? 그렇게함으로써 성능을 향상시킬 수 있습니까?

답변

2

당신이 실제로하고있는 것은 (당신이 Hibernate의 세션에서 JDBC 커넥션을 얻고있다하더라도) SQL을 실행하기 위해 JDBC를 사용하는 것이다. JDBC를 사용하면 다음과 같이 할 수 있습니다.

public void store(int[] params1, int[] params2) { 
    Connection con = session.connection(); 
    boolean initialAutocommitSetting = connection con.getAutoCommit(); 
    //disable autocommit 
    con.setAutoCommit(false); 
    //you only need one statement object: 
    CallableStatement stmt = con.prepareCall("{ call changesalary(?,?) }"); 

    for (int i = 0; i < params1.length; i++) {  
     stmt.setInt(1, params1[i]); 
     stmt.setInt(2, params2[i]); 
     //for each call, add the set of parameters as needed and call addBatch(); 
     stmt.addBatch(); 
    } 
    //when you're done, execute your (batch) statement and see how many updates you got 
    int [] updatesCount=stmt.executeBatch(); 

    //manually commit 
    con.commit(); 

    if(updatesCount!=i) { 
     //some updates didn't work 
    } 

    //return connection to initial autocommit setting: 
    connection.setAutoCommit(initialAutocommitSetting); 
} 

희망이 있습니다. Javadocs : CallableStatement, Statement

+0

감사합니다. 완벽하게 작동했습니다. – aksamit

관련 문제