1 16 package scriptella.jdbc; 17 18 import scriptella.util.IOUtils; 19 import scriptella.util.LRUMap; 20 21 import java.io.Closeable ; 22 import java.sql.Connection ; 23 import java.sql.SQLException ; 24 import java.util.List ; 25 import java.util.Map ; 26 27 33 class StatementCache implements Closeable { 34 private Map<String , StatementWrapper> map; 35 private final Connection connection; 36 37 42 public StatementCache(Connection connection, final int size) { 43 this.connection = connection; 44 if (size > 0) { map = new LRUMap<String , StatementWrapper>(size) { 46 protected void onEldestEntryRemove(Map.Entry<String , StatementWrapper> eldest) { 47 eldest.getValue().close(); 48 } 49 }; 50 } 51 } 52 53 65 public StatementWrapper prepare(final String sql, final List <Object > params, final JdbcTypesConverter converter) throws SQLException { 66 StatementWrapper sw = map == null ? null : map.get(sql); 67 68 if (sw == null) { if (params==null || params.isEmpty()) { 70 sw = create(sql, converter); 71 } else { 72 sw = prepare(sql, converter); 73 } 74 put(sql, sw); 75 } else if (sw instanceof StatementWrapper.Simple) { 76 sw.close(); put(sql, sw = prepare(sql, converter)); 79 } 80 sw.setParameters(params); 81 return sw; 82 } 83 84 87 protected StatementWrapper.Simple create(final String sql, final JdbcTypesConverter converter) throws SQLException { 88 return new StatementWrapper.Simple(connection.createStatement(), sql, converter); 89 } 90 91 94 protected StatementWrapper.Prepared prepare(final String sql, final JdbcTypesConverter converter) throws SQLException { 95 return new StatementWrapper.Prepared(connection.prepareStatement(sql), converter); 96 } 97 98 99 private void put(String key, StatementWrapper entry) { 100 if (map != null) { 101 map.put(key, entry); 102 } 103 } 104 105 111 public void releaseStatement(StatementWrapper sw) { 112 if (sw == null) { 113 throw new IllegalArgumentException ("Released statement cannot be null"); 114 } 115 if (map == null) { 117 sw.close(); 118 } else { 119 sw.clear(); 120 } 121 } 122 123 public void close() { 124 if (map != null) { 125 IOUtils.closeSilently(map.values()); 127 map = null; 128 } 129 } 130 131 } 132 | Popular Tags |