/
JdbcSqlTemplate.java
927 lines (848 loc) · 35 KB
/
JdbcSqlTemplate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jumpmind.db.sql;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.jumpmind.db.platform.DatabaseInfo;
import org.jumpmind.exception.IoException;
import org.jumpmind.util.LinkedCaseInsensitiveMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobHandler;
public class JdbcSqlTemplate extends AbstractSqlTemplate implements ISqlTemplate {
static final Logger log = LoggerFactory.getLogger(JdbcSqlTemplate.class);
protected DataSource dataSource;
protected boolean requiresAutoCommitFalseToSetFetchSize = false;
protected SqlTemplateSettings settings;
protected SymmetricLobHandler lobHandler;
protected Boolean supportsGetGeneratedKeys = null;
protected int[] primaryKeyViolationCodes;
protected String[] primaryKeyViolationSqlStates;
protected int[] foreignKeyViolationCodes;
protected String[] foreignKeyViolationSqlStates;
protected int isolationLevel;
public JdbcSqlTemplate(DataSource dataSource, SqlTemplateSettings settings,
SymmetricLobHandler lobHandler, DatabaseInfo databaseInfo) {
this.dataSource = dataSource;
this.settings = settings == null ? new SqlTemplateSettings() : settings;
this.lobHandler = lobHandler == null ? new SymmetricLobHandler(new DefaultLobHandler())
: lobHandler;
this.isolationLevel = databaseInfo.getMinIsolationLevelToPreventPhantomReads();
}
protected Connection getConnection() throws SQLException {
return this.dataSource.getConnection();
}
public DataSource getDataSource() {
return dataSource;
}
public boolean isRequiresAutoCommitFalseToSetFetchSize() {
return requiresAutoCommitFalseToSetFetchSize;
}
public void setSettings(SqlTemplateSettings settings) {
this.settings = settings;
}
public SqlTemplateSettings getSettings() {
return settings;
}
public SymmetricLobHandler getLobHandler() {
return lobHandler;
}
public <T> ISqlReadCursor<T> queryForCursor(String sql, ISqlRowMapper<T> mapper, Object[] args,
int[] types) {
logSql(sql, args);
return new JdbcSqlReadCursor<T>(this, mapper, sql, args, types);
}
public int getIsolationLevel() {
return isolationLevel;
}
public void setIsolationLevel(int isolationLevel) {
this.isolationLevel = isolationLevel;
}
public <T> T queryForObject(final String sql, final Class<T> clazz, final Object... args) {
logSql(sql, args);
return execute(new IConnectionCallback<T>() {
public T execute(Connection con) throws SQLException {
T result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(expandSql(sql, args));
ps.setQueryTimeout(settings.getQueryTimeout());
setValues(ps, expandArgs(sql, args));
rs = ps.executeQuery();
if (rs.next()) {
result = getObjectFromResultSet(rs, clazz);
}
} finally {
close(rs);
close(ps);
}
return result;
}
});
}
@Deprecated
public byte[] queryForBlob(final String sql, final Object... args) {
return queryForBlob(sql, -1, null, args);
}
public byte[] queryForBlob(final String sql, final int jdbcTypeCode, final String jdbcTypeName,
final Object... args) {
logSql(sql, args);
return execute(new IConnectionCallback<byte[]>() {
public byte[] execute(Connection con) throws SQLException {
if (lobHandler.needsAutoCommitFalseForBlob(jdbcTypeCode, jdbcTypeName)) {
con.setAutoCommit(false);
}
byte[] result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(sql);
ps.setQueryTimeout(settings.getQueryTimeout());
setValues(ps, args);
rs = ps.executeQuery();
if (rs.next()) {
result = lobHandler.getBlobAsBytes(rs, 1, jdbcTypeCode, jdbcTypeName);
}
} finally {
if (lobHandler.needsAutoCommitFalseForBlob(jdbcTypeCode, jdbcTypeName)
&& con != null) {
con.setAutoCommit(true);
}
close(rs);
close(ps);
}
return result;
}
});
}
public String queryForClob(final String sql, final Object... args) {
logSql(sql, args);
return execute(new IConnectionCallback<String>() {
public String execute(Connection con) throws SQLException {
String result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(sql);
ps.setQueryTimeout(settings.getQueryTimeout());
setValues(ps, args);
rs = ps.executeQuery();
if (rs.next()) {
result = lobHandler.getClobAsString(rs, 1);
}
} finally {
close(rs);
close(ps);
}
return result;
}
});
}
public Map<String, Object> queryForMap(final String sql, final Object... args) {
logSql(sql, args);
return execute(new IConnectionCallback<Map<String, Object>>() {
public Map<String, Object> execute(Connection con) throws SQLException {
Map<String, Object> result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement(sql);
ps.setQueryTimeout(settings.getQueryTimeout());
if (args != null && args.length > 0) {
setValues(ps, args);
}
rs = ps.executeQuery();
if (rs.next()) {
ResultSetMetaData meta = rs.getMetaData();
int colCount = meta.getColumnCount();
result = new LinkedCaseInsensitiveMap<Object>(colCount);
for (int i = 1; i <= colCount; i++) {
String key = meta.getColumnName(i);
Object value = rs.getObject(i);
if (value instanceof Blob) {
Blob blob = (Blob) value;
try {
value = IOUtils.toByteArray(blob.getBinaryStream());
} catch (IOException e) {
throw new IoException(e);
}
} else if (value instanceof Clob) {
Clob clob = (Clob) value;
try {
value = IOUtils.toByteArray(clob.getCharacterStream());
} catch (IOException e) {
throw new IoException(e);
}
} else if (value != null) {
Class<?> clazz = value.getClass();
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null
&& superClazz.getName().equals("oracle.sql.Datum")) {
try {
Method method = superClazz.getMethod("toJdbc");
value = method.invoke(value);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
result.put(key, value);
}
}
} finally {
close(rs);
close(ps);
}
return result;
}
});
}
public ISqlTransaction startSqlTransaction() {
return new JdbcSqlTransaction(this);
}
public int update(final String sql, final Object[] args, final int[] types) {
logSql(sql, args);
return execute(new IConnectionCallback<Integer>() {
public Integer execute(Connection con) throws SQLException {
if (args == null) {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.setQueryTimeout(settings.getQueryTimeout());
stmt.execute(sql);
return stmt.getUpdateCount();
} finally {
close(stmt);
}
} else {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(sql);
ps.setQueryTimeout(settings.getQueryTimeout());
if (types != null) {
setValues(ps, args, types, getLobHandler()
.getDefaultHandler());
} else {
setValues(ps, args);
}
ps.execute();
return ps.getUpdateCount();
} finally {
close(ps);
}
}
}
});
}
public int update(boolean autoCommit, boolean failOnError, int commitRate, String... sql) {
return update(autoCommit, failOnError, commitRate, null, sql);
}
public int update(boolean autoCommit, boolean failOnError, int commitRate,
ISqlResultsListener resultsListener, String... sql) {
return this.update(autoCommit, failOnError, true, true,
commitRate, resultsListener, new ListSqlStatementSource(sql));
}
public int update(final boolean autoCommit, final boolean failOnError, final boolean failOnDrops,
final boolean failOnSequenceCreate, final int commitRate, final ISqlResultsListener resultsListener, final ISqlStatementSource source) {
return execute(new IConnectionCallback<Integer>() {
public Integer execute(Connection con) throws SQLException {
int totalUpdateCount = 0;
boolean oldAutoCommitSetting = con.getAutoCommit();
Statement stmt = null;
try {
con.setAutoCommit(autoCommit);
stmt = con.createStatement();
int statementCount = 0;
for (String statement = source.readSqlStatement(); statement != null; statement = source
.readSqlStatement()) {
logSql(statement, null);
try {
boolean hasResults = stmt.execute(statement);
int updateCount = stmt.getUpdateCount();
totalUpdateCount += updateCount;
int rowsRetrieved = 0;
if (hasResults) {
ResultSet rs = null;
try {
rs = stmt.getResultSet();
while (rs.next()) {
rowsRetrieved++;
}
} finally {
close(rs);
}
}
if (resultsListener != null) {
resultsListener.sqlApplied(statement, updateCount, rowsRetrieved,
statementCount);
}
statementCount++;
if (statementCount % commitRate == 0 && !autoCommit) {
con.commit();
}
} catch (SQLException ex) {
boolean isDrop = statement.toLowerCase().trim().startsWith("drop");
boolean isSequenceCreate = statement.toLowerCase().trim().startsWith("create sequence");
if (resultsListener != null) {
resultsListener.sqlErrored(statement, translate(statement, ex),
statementCount, isDrop, isSequenceCreate);
}
if ((isDrop && !failOnDrops) || (isSequenceCreate && !failOnSequenceCreate)) {
log.debug("{}. Failed to execute: {}", ex.getMessage(), statement);
} else {
log.warn("{}. Failed to execute: {}", ex.getMessage(), statement);
if (failOnError) {
throw ex;
}
}
}
}
if (!autoCommit) {
con.commit();
}
return totalUpdateCount;
} catch (SQLException ex) {
if (!autoCommit) {
con.rollback();
}
throw ex;
} finally {
close(stmt);
con.setAutoCommit(oldAutoCommitSetting);
}
}
});
}
public void testConnection() {
execute(new IConnectionCallback<Boolean>() {
public Boolean execute(Connection con) throws SQLException {
return true;
}
});
}
public <T> T execute(IConnectionCallback<T> callback) {
Connection c = null;
try {
c = getConnection();
return callback.execute(c);
} catch (SQLException ex) {
throw translate(ex);
} finally {
close(c);
}
}
/**
* Determine the column name to use. The column name is determined based on
* a lookup using ResultSetMetaData.
* <p>
* This method implementation takes into account recent clarifications
* expressed in the JDBC 4.0 specification:
* <p>
* <i>columnLabel - the label for the column specified with the SQL AS
* clause. If the SQL AS clause was not specified, then the label is the
* name of the column</i>.
*
* @return the column name to use
* @param resultSetMetaData
* the current meta data to use
* @param columnIndex
* the index of the column for the look up
* @throws SQLException
* in case of lookup failure
*/
public static String lookupColumnName(ResultSetMetaData resultSetMetaData, int columnIndex)
throws SQLException {
String name = resultSetMetaData.getColumnLabel(columnIndex);
if (name == null || name.length() < 1) {
name = resultSetMetaData.getColumnName(columnIndex);
}
return name;
}
/**
* Retrieve a JDBC column value from a ResultSet, using the most appropriate
* value type. The returned value should be a detached value object, not
* having any ties to the active ResultSet: in particular, it should not be
* a Blob or Clob object but rather a byte array respectively String
* representation.
* <p>
* Uses the <code>getObject(index)</code> method, but includes additional
* "hacks" to get around Oracle 10g returning a non-standard object for its
* TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
* leaving out the time portion: These columns will explicitly be extracted
* as standard <code>java.sql.Timestamp</code> object.
*
* @param rs
* is the ResultSet holding the data
* @param index
* is the column index
* @return the value object
* @throws SQLException
* if thrown by the JDBC API
* @see java.sql.Blob
* @see java.sql.Clob
* @see java.sql.Timestamp
*/
public static Object getResultSetValue(ResultSet rs, int index) throws SQLException {
Object obj = rs.getObject(index);
ResultSetMetaData metaData = rs.getMetaData();
String className = null;
if (obj != null) {
className = obj.getClass().getName();
}
if (obj instanceof Blob) {
Blob blob = (Blob) obj;
InputStream is = blob.getBinaryStream();
try {
obj = IOUtils.toByteArray(is);
} catch (IOException e) {
throw new SqlException(e);
} finally {
IOUtils.closeQuietly(is);
}
} else if (obj instanceof Clob) {
Clob clob = (Clob) obj;
Reader reader = clob.getCharacterStream();
try {
obj = IOUtils.toString(reader);
} catch (IOException e) {
throw new SqlException(e);
} finally {
IOUtils.closeQuietly(reader);
}
} else if (className != null && ("oracle.sql.TIMESTAMP".equals(className))) {
obj = rs.getTimestamp(index);
} else if (className != null && "oracle.sql.TIMESTAMPTZ".equals(className)) {
obj = rs.getString(index);
} else if (className != null && className.startsWith("oracle.sql.DATE")) {
String metaDataClassName = metaData.getColumnClassName(index);
if ("java.sql.Timestamp".equals(metaDataClassName)
|| "oracle.sql.TIMESTAMP".equals(metaDataClassName)) {
obj = rs.getTimestamp(index);
} else {
obj = rs.getDate(index);
}
} else if (obj instanceof java.sql.Date) {
String metaDataClassName = metaData.getColumnClassName(index);
if ("java.sql.Timestamp".equals(metaDataClassName)) {
obj = rs.getTimestamp(index);
}
} else if (obj instanceof Timestamp) {
String typeName = metaData.getColumnTypeName(index);
if (typeName != null && typeName.equals("timestamptz")) {
obj = rs.getString(index);
}
}
return obj;
}
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException ex) {
}
}
public static void close(PreparedStatement ps) {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException ex) {
}
}
public static void close(Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException ex) {
}
}
public static void close(boolean autoCommitValue, Connection c) {
try {
if (c != null) {
c.setAutoCommit(autoCommitValue);
}
} catch (SQLException ex) {
} finally {
close(c);
}
}
public static void close(boolean autoCommitValue, int transactionIsolationLevel, Connection c) {
try {
if (c != null) {
c.setAutoCommit(autoCommitValue);
if (c.getTransactionIsolation() != transactionIsolationLevel) {
c.setTransactionIsolation(transactionIsolationLevel);
}
}
} catch (SQLException ex) {
} finally {
close(c);
}
}
public static void close(Connection c) {
try {
if (c != null) {
c.close();
}
} catch (SQLException ex) {
}
}
public int getDatabaseMajorVersion() {
return execute(new IConnectionCallback<Integer>() {
public Integer execute(Connection con) throws SQLException {
return con.getMetaData().getDatabaseMajorVersion();
}
});
}
public int getDatabaseMinorVersion() {
return execute(new IConnectionCallback<Integer>() {
public Integer execute(Connection con) throws SQLException {
return con.getMetaData().getDatabaseMinorVersion();
}
});
}
public String getDatabaseProductName() {
return execute(new IConnectionCallback<String>() {
public String execute(Connection con) throws SQLException {
return con.getMetaData().getDatabaseProductName();
}
});
}
public boolean isStoresMixedCaseQuotedIdentifiers() {
return execute(new IConnectionCallback<Boolean>() {
public Boolean execute(Connection con) throws SQLException {
return con.getMetaData().storesMixedCaseQuotedIdentifiers();
}
});
}
public boolean isStoresUpperCaseIdentifiers() {
return execute(new IConnectionCallback<Boolean>() {
public Boolean execute(Connection con) throws SQLException {
return con.getMetaData().storesUpperCaseIdentifiers();
}
});
}
public boolean isStoresLowerCaseIdentifiers() {
return execute(new IConnectionCallback<Boolean>() {
public Boolean execute(Connection con) throws SQLException {
return con.getMetaData().storesLowerCaseIdentifiers();
}
});
}
public String getDatabaseProductVersion() {
return execute(new IConnectionCallback<String>() {
public String execute(Connection con) throws SQLException {
return con.getMetaData().getDatabaseProductVersion();
}
});
}
public String getDriverName() {
return execute(new IConnectionCallback<String>() {
public String execute(Connection con) throws SQLException {
return con.getMetaData().getDriverName();
}
});
}
public String getDriverVersion() {
return execute(new IConnectionCallback<String>() {
public String execute(Connection con) throws SQLException {
return con.getMetaData().getDriverVersion();
}
});
}
public Set<String> getSqlKeywords() {
return execute(new IConnectionCallback<Set<String>>() {
public Set<String> execute(Connection con) throws SQLException {
DatabaseMetaData sqlTemplateData = con.getMetaData();
return new HashSet<String>(Arrays.asList(sqlTemplateData.getSQLKeywords()
.split(",")));
}
});
}
public boolean supportsGetGeneratedKeys() {
if (supportsGetGeneratedKeys == null) {
supportsGetGeneratedKeys = execute(new IConnectionCallback<Boolean>() {
public Boolean execute(Connection con) throws SQLException {
return con.getMetaData().supportsGetGeneratedKeys();
}
});
}
return supportsGetGeneratedKeys;
}
public boolean supportsReturningKeys() {
return false;
}
protected boolean allowsNullForIdentityColumn() {
return true;
}
protected String getSelectLastInsertIdSql(String sequenceName) {
throw new UnsupportedOperationException();
}
public long insertWithGeneratedKey(final String sql, final String column,
final String sequenceName, final Object[] args, final int[] types) {
return execute(new IConnectionCallback<Long>() {
public Long execute(Connection conn) throws SQLException {
return insertWithGeneratedKey(conn, sql, column, sequenceName, args, types);
}
});
}
protected long insertWithGeneratedKey(Connection conn, String sql, String column,
String sequenceName, Object[] args, int[] types) throws SQLException {
long key = 0;
PreparedStatement ps = null;
try {
boolean supportsGetGeneratedKeys = supportsGetGeneratedKeys();
boolean supportsReturningKeys = supportsReturningKeys();
if (allowsNullForIdentityColumn()) {
if (supportsGetGeneratedKeys) {
ps = conn.prepareStatement(sql, new int[] { 1 });
} else if (supportsReturningKeys) {
ps = conn.prepareStatement(sql + " returning " + column);
} else {
ps = conn.prepareStatement(sql);
}
} else {
String replaceSql = sql.replaceFirst("\\([\"|\\w]*,", "(").replaceFirst("\\(null,",
"(");
if (supportsGetGeneratedKeys) {
ps = conn.prepareStatement(replaceSql, Statement.RETURN_GENERATED_KEYS);
} else {
ps = conn.prepareStatement(replaceSql);
}
}
ps.setQueryTimeout(settings.getQueryTimeout());
setValues(ps, args, types, lobHandler.getDefaultHandler());
ResultSet rs = null;
if (supportsGetGeneratedKeys) {
ps.execute();
try {
rs = ps.getGeneratedKeys();
if (rs.next()) {
key = rs.getLong(1);
}
} finally {
close(rs);
}
} else if (supportsReturningKeys) {
try {
rs = ps.executeQuery();
if (rs.next()) {
key = rs.getLong(1);
}
} finally {
close(rs);
}
} else {
Statement st = null;
ps.execute();
try {
st = conn.createStatement();
rs = st.executeQuery(getSelectLastInsertIdSql(sequenceName));
if (rs.next()) {
key = rs.getLong(1);
}
} finally {
close(rs);
close(st);
}
}
} finally {
close(ps);
}
return key;
}
public boolean isUniqueKeyViolation(Throwable ex) {
boolean primaryKeyViolation = false;
if (primaryKeyViolationCodes != null || primaryKeyViolationSqlStates != null) {
SQLException sqlEx = findSQLException(ex);
if (sqlEx != null) {
if (primaryKeyViolationCodes != null) {
int errorCode = sqlEx.getErrorCode();
for (int primaryKeyViolationCode : primaryKeyViolationCodes) {
if (primaryKeyViolationCode == errorCode) {
primaryKeyViolation = true;
break;
}
}
}
if (primaryKeyViolationSqlStates != null) {
String sqlState = sqlEx.getSQLState();
if (sqlState != null) {
for (String primaryKeyViolationSqlState : primaryKeyViolationSqlStates) {
if (primaryKeyViolationSqlState != null
&& primaryKeyViolationSqlState.equals(sqlState)) {
primaryKeyViolation = true;
break;
}
}
}
}
}
}
return primaryKeyViolation;
}
public boolean isForeignKeyViolation(Throwable ex) {
boolean foreignKeyViolation = false;
if (foreignKeyViolationCodes != null || foreignKeyViolationSqlStates != null) {
SQLException sqlEx = findSQLException(ex);
if (sqlEx != null) {
if (foreignKeyViolationCodes != null) {
int errorCode = sqlEx.getErrorCode();
for (int foreignKeyViolationCode : foreignKeyViolationCodes) {
if (foreignKeyViolationCode == errorCode) {
foreignKeyViolation = true;
break;
}
}
}
if (foreignKeyViolationSqlStates != null) {
String sqlState = sqlEx.getSQLState();
if (sqlState != null) {
for (String foreignKeyViolationSqlState : foreignKeyViolationSqlStates) {
if (foreignKeyViolationSqlState != null
&& foreignKeyViolationSqlState.equals(sqlState)) {
foreignKeyViolation = true;
break;
}
}
}
}
}
}
return foreignKeyViolation;
}
protected SQLException findSQLException(Throwable ex) {
if (ex instanceof SQLException) {
return (SQLException) ex;
} else {
Throwable cause = ex.getCause();
if (cause != null && !cause.equals(ex)) {
return findSQLException(cause);
}
}
return null;
}
@SuppressWarnings("unchecked")
public <T> T getObjectFromResultSet(ResultSet rs, Class<T> clazz) throws SQLException {
T result;
if (Date.class.isAssignableFrom(clazz)) {
result = (T) rs.getTimestamp(1);
} else if (String.class.isAssignableFrom(clazz)) {
result = (T) rs.getString(1);
} else if (Long.class.isAssignableFrom(clazz)) {
result = (T)new Long(rs.getLong(1));
} else if (Integer.class.isAssignableFrom(clazz)) {
result = (T)new Integer(rs.getInt(1));
} else if (Float.class.isAssignableFrom(clazz)) {
result = (T)new Float(rs.getFloat(1));
} else if (Double.class.isAssignableFrom(clazz)) {
result = (T)new Double(rs.getDouble(1));
} else if (BigDecimal.class.isAssignableFrom(clazz)) {
result = (T)rs.getBigDecimal(1);
} else {
result = (T) rs.getObject(1);
}
return result;
}
public void setValues(PreparedStatement ps, Object[] args, int[] argTypes,
LobHandler lobHandler) throws SQLException {
for (int i = 1; i <= args.length; i++) {
Object arg = args[i - 1];
int argType = argTypes != null && argTypes.length >= i ? argTypes[i - 1] : SqlTypeValue.TYPE_UNKNOWN;
if (argType == Types.BLOB && lobHandler != null && arg instanceof byte[]) {
lobHandler.getLobCreator().setBlobAsBytes(ps, i, (byte[]) arg);
} else if (argType == Types.BLOB && lobHandler != null && arg instanceof String) {
lobHandler.getLobCreator().setBlobAsBytes(ps, i, arg.toString().getBytes());
} else if (argType == Types.CLOB && lobHandler != null) {
lobHandler.getLobCreator().setClobAsString(ps, i, (String) arg);
} else if (argType == Types.DECIMAL && arg != null) {
setDecimalValue(ps, i, arg, argType);
} else {
StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
}
}
}
protected void setDecimalValue(PreparedStatement ps, int i, Object arg, int argType) throws SQLException {
StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
}
protected int verifyArgType(Object arg, int argType) {
if (argType == -101 || argType == Types.OTHER) {
return SqlTypeValue.TYPE_UNKNOWN;
} else if ((argType == Types.INTEGER && arg instanceof BigInteger) ||
(argType == Types.BIGINT && arg instanceof BigDecimal)) {
return Types.DECIMAL;
} else {
return argType;
}
}
public void setValues(PreparedStatement ps, Object[] args) throws SQLException {
if (args != null) {
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
doSetValue(ps, i + 1, arg);
}
}
}
/**
* Set the value for prepared statements specified parameter index using the
* passed in value. This method can be overridden by sub-classes if needed.
*
* @param ps
* the PreparedStatement
* @param parameterPosition
* index of the parameter position
* @param argValue
* the value to set
* @throws SQLException
*/
public void doSetValue(PreparedStatement ps, int parameterPosition, Object argValue)
throws SQLException {
StatementCreatorUtils.setParameterValue(ps, parameterPosition, SqlTypeValue.TYPE_UNKNOWN, argValue);
}
}