1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.fosstrak.epcis.repository.capture;
22
23 import java.sql.Connection;
24 import java.sql.PreparedStatement;
25 import java.sql.SQLException;
26 import java.util.HashMap;
27 import java.util.LinkedHashMap;
28 import java.util.Map;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32
33
34
35
36
37
38
39
40 public class CaptureOperationsSession {
41
42 private static final Log LOG = LogFactory.getLog(CaptureOperationsSession.class);
43
44 private Connection connection;
45
46 private Map<String, PreparedStatement> inserts = new LinkedHashMap<String, PreparedStatement>();
47 private Map<String, PreparedStatement> batchInserts = new LinkedHashMap<String, PreparedStatement>();
48 private Map<String, PreparedStatement> selects = new HashMap<String, PreparedStatement>();
49
50 public CaptureOperationsSession(final Connection connection) {
51 this.connection = connection;
52 }
53
54 public PreparedStatement getInsert(final String sql) throws SQLException {
55 PreparedStatement ps = inserts.get(sql);
56 if (ps == null) {
57 ps = connection.prepareStatement(sql);
58 inserts.put(sql, ps);
59 }
60 ps.clearParameters();
61 return ps;
62 }
63
64 public PreparedStatement getBatchInsert(final String sql) throws SQLException {
65 PreparedStatement ps = batchInserts.get(sql);
66 if (ps == null) {
67 ps = connection.prepareStatement(sql);
68 batchInserts.put(sql, ps);
69 }
70 ps.clearParameters();
71 return ps;
72 }
73
74 public PreparedStatement getSelect(final String sql) throws SQLException {
75 PreparedStatement ps = selects.get(sql);
76 if (ps == null) {
77 ps = connection.prepareStatement(sql);
78 selects.put(sql, ps);
79 }
80 ps.clearParameters();
81 return ps;
82 }
83
84 public Connection getConnection() {
85 return connection;
86 }
87
88 public void commit() throws SQLException {
89 for (PreparedStatement ps : batchInserts.values()) {
90 ps.executeBatch();
91 }
92 connection.commit();
93 }
94
95 public void rollback() throws SQLException {
96 connection.rollback();
97 }
98
99 public void close() throws SQLException {
100 for (PreparedStatement ps : inserts.values()) {
101 try {
102 ps.close();
103 } catch (SQLException e) {
104 LOG.warn("Error closing PreparedStatement: " + e.toString() + ". Will continue ... ");
105 }
106 }
107 for (PreparedStatement ps : batchInserts.values()) {
108 try {
109 ps.close();
110 } catch (SQLException e) {
111 LOG.warn("Error closing PreparedStatement: " + e.toString() + ". Will continue ... ");
112 }
113 }
114 for (PreparedStatement ps : selects.values()) {
115 try {
116 ps.close();
117 } catch (SQLException e) {
118 LOG.warn("Error closing PreparedStatement: " + e.toString() + ". Will continue ... ");
119 }
120 }
121 connection.close();
122 }
123
124 }