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.query;
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.Map;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31
32
33
34
35
36
37 public class QueryOperationsSession {
38
39 private static final Log LOG = LogFactory.getLog(QueryOperationsSession.class);
40
41 private Connection connection;
42
43 private Map<String, PreparedStatement> namedStatements = new HashMap<String, PreparedStatement>();
44
45 public QueryOperationsSession(final Connection connection) {
46 this.connection = connection;
47 }
48
49
50
51
52
53
54
55
56
57 public PreparedStatement getPreparedStatement(final String sql) throws SQLException {
58 PreparedStatement ps = namedStatements.get(sql);
59 if (ps == null) {
60 ps = connection.prepareStatement(sql);
61 if (LOG.isDebugEnabled()) {
62 LOG.debug("Prepared SQL statement: " + sql);
63 }
64 namedStatements.put(sql, ps);
65 }
66 ps.clearParameters();
67 return ps;
68 }
69
70 public Connection getConnection() {
71 return connection;
72 }
73
74 public void rollback() throws SQLException {
75 connection.rollback();
76 }
77
78 public void commit() throws SQLException {
79 connection.commit();
80 }
81
82 public void close() throws SQLException {
83 for (PreparedStatement ps : namedStatements.values()) {
84 try {
85 ps.close();
86 } catch (SQLException e) {
87 LOG.warn("Error closing prepared statement: " + e.toString() + ". Will continue ... ");
88 }
89 }
90 connection.close();
91 LOG.debug("Database connection for session closed");
92 }
93 }