01: package net.sourceforge.jaxor;
02:
03: import java.sql.Connection;
04: import java.sql.PreparedStatement;
05: import java.sql.SQLException;
06: import java.util.Collection;
07: import java.util.Iterator;
08:
09: /**
10: * Created By: Mike
11: * Date: Nov 14, 2003
12: * Time: 8:12:53 PM
13: *
14: * Last Checkin: $Author: mrettig $
15: * Date: $Date: 2004/02/13 05:05:38 $
16: * Revision: $Revision: 1.8 $
17: */
18: public class CommitBatch {
19:
20: private final Collection _changes;
21:
22: public CommitBatch(Collection changes) {
23: _changes = changes;
24: }
25:
26: public void execute(Connection conn, boolean batchUpdates)
27: throws SQLException {
28: if (!batchUpdates) {
29: noBatching(conn);
30: } else {
31: batch(conn);
32: }
33: }
34:
35: public void batch(Connection conn) throws SQLException {
36: EntityChange last = null;
37: PreparedStatement lastStmt = null;
38: try {
39: for (Iterator iterator = _changes.iterator(); iterator
40: .hasNext();) {
41: EntityChange entityChange = (EntityChange) iterator
42: .next();
43: boolean batching = entityChange.canBatchWithLast(last);
44: if (batching) {
45: entityChange.addToBatch(lastStmt);
46: } else if (lastStmt != null) {
47: lastStmt.executeBatch();
48: lastStmt.close();
49: lastStmt = null;
50: }
51: if (!batching) {
52: lastStmt = entityChange.execute(conn);
53: if (lastStmt != null)
54: lastStmt.addBatch();
55: last = entityChange;
56: }
57: }
58: if (lastStmt != null) {
59: lastStmt.executeBatch();
60: }
61: } finally {
62: if (lastStmt != null) {
63: try {
64: lastStmt.close();
65: } catch (SQLException e) {
66: e.printStackTrace();
67: }
68: }
69: }
70: }
71:
72: private void noBatching(Connection conn) throws SQLException {
73: for (Iterator iterator = _changes.iterator(); iterator
74: .hasNext();) {
75: EntityChange entityChange = (EntityChange) iterator.next();
76: PreparedStatement stmt = entityChange.execute(conn);
77: if (stmt != null) {
78: stmt.execute();
79: stmt.close();
80: }
81: }
82: }
83: }
|