KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > db > DbQuery


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.db;
4
5 import jodd.util.collection.Bag;
6 import jodd.util.collection.HashBag;
7 import jodd.util.collection.IntArrayList;
8 import jodd.mutable.*;
9 import jodd.bean.BeanUtil;
10
11 import java.sql.*;
12 import java.util.Iterator JavaDoc;
13 import java.util.Map JavaDoc;
14 import java.math.BigDecimal JavaDoc;
15 import java.math.BigInteger JavaDoc;
16 import java.net.URL JavaDoc;
17
18 /**
19  * Encapsulates {@link Statement} and all its operations.
20  * <p>
21  * It may be:
22  * <ol>
23  * <li>used in an un-managed way, created directly from connection;</li>
24  * <li>managed by {@link DbSession};</li>
25  * <li>managed by {@link jodd.db.DbThreadSession}.</li>
26  * </ol>
27  */

28 public class DbQuery {
29
30     /**
31      * If set to <code>true</code> all created statements will be prepared.
32      */

33     public static boolean FORCE_PREPARED_STATEMENTS = false;
34
35
36     protected static int totalOpenResultSetCount = 0;
37
38     /**
39      * Returns total number of open result sets.
40      * @see #getOpenResultSetCount()
41      */

42     public static int getTotalOpenResultSetCount() {
43         return totalOpenResultSetCount;
44     }
45
46     // ---------------------------------------------------------------- params
47

48     protected Statement statement;
49     protected PreparedStatement preparedStatement;
50     protected Bag resultSets;
51     protected DbQueryMode mode;
52     protected DbQueryParser query;
53     protected Connection connection;
54
55     protected DbSession session;
56     /**
57      * Default {@link DbQueryMode} for all queries.
58      */

59     public static DbQueryMode DEFAULT_QUERY_MODE = new DbQueryMode();
60
61     /**
62      * Returns query sql string.
63      */

64     public String JavaDoc getQueryString() {
65         if ((preparedStatement != null) && (preparedStatement instanceof LoggablePreparedStatement)) {
66             return ((LoggablePreparedStatement) preparedStatement).getQueryString();
67         }
68         if (query != null) {
69             return query.sql;
70         }
71         return null;
72     }
73
74     public String JavaDoc toString() {
75         return getQueryString();
76     }
77     
78
79     // ---------------------------------------------------------------- ctors
80

81     /**
82      * Creates new query,
83      */

84     public DbQuery(Connection conn, String JavaDoc sqlString) {
85         init(conn, sqlString, DEFAULT_QUERY_MODE);
86     }
87
88     /**
89      * Creates new query.
90      */

91     public DbQuery(Connection conn, String JavaDoc sqlString, DbQueryMode mode) {
92         init(conn, sqlString, mode);
93     }
94
95     /**
96      * Creates a new query from {@link DbSession}.
97      */

98     public DbQuery(DbSession session, String JavaDoc sqlString, DbQueryMode mode) {
99         this.session = session;
100         session.attachQuery(this);
101         init(session.getConnection(), sqlString, mode);
102     }
103
104     /**
105      * Creates a new query from {@link DbSession}.
106      */

107     public DbQuery(DbSession session, String JavaDoc sqlString) {
108         this(session, sqlString, DEFAULT_QUERY_MODE);
109     }
110
111
112     /**
113      * Creates a new query from {@link DbThreadSession} that is
114      * assigned to current thread.
115      * @see jodd.db.DbThreadSession#getCurrentSession()
116      */

117     public DbQuery(String JavaDoc sqlString, DbQueryMode mode) {
118         DbSession session = DbThreadSession.getCurrentSession();
119         if (session == null) {
120             throw new DbSqlException("No session associated to current thread.");
121         }
122         session.attachQuery(this);
123         init(session.getConnection(), sqlString, mode);
124     }
125
126     /**
127      * Creates a new query from {@link DbThreadSession} that is
128      * assigned to current thread.
129      */

130     public DbQuery(String JavaDoc sqlString) {
131         this(sqlString, DEFAULT_QUERY_MODE);
132     }
133
134
135     /**
136      * Initializes query. Must be called from ctors.
137      */

138     protected void init(Connection connection, String JavaDoc sqlString, DbQueryMode mode) {
139         this.connection = connection;
140         this.mode = mode;
141         if (sqlString == null) {
142             return;
143         }
144         init(sqlString);
145     }
146
147     protected void init(String JavaDoc sqlString) {
148         this.query = new DbQueryParser(sqlString);
149         if (statement == null) {
150             if ((FORCE_PREPARED_STATEMENTS == false) && (query.prepared == false)) {
151                 try {
152                     statement = connection.createStatement(mode.getType(), mode.getConcurrencyType());
153                 } catch (SQLException sex) {
154                     throw new DbSqlException("Unable to create statement.", sex);
155                 }
156             } else {
157                 try {
158                     if (mode.isDebug() == true) {
159                         statement = new LoggablePreparedStatement(connection, query.sql, mode.getType(), mode.getConcurrencyType());
160                     } else {
161                         statement = connection.prepareStatement(query.sql, mode.getType(), mode.getConcurrencyType());
162                     }
163                 } catch (SQLException sex) {
164                     throw new DbSqlException("Unable to create prepared statement.", sex);
165                 }
166                 preparedStatement = (PreparedStatement) statement;
167             }
168         }
169     }
170
171
172     /**
173      * Returns <code>true</code> if query is closed.
174      */

175     public boolean isClosed() {
176         return (statement == null);
177     }
178
179     public boolean isActive() {
180         return (statement != null);
181     }
182
183
184     protected void checkActive() {
185         if (statement == null) {
186             throw new DbSqlException("Query is closed.");
187         }
188     }
189
190     /**
191      * Closes the query and all created results sets.
192      * No further usage is possible after the query is closed.
193      */

194     public void close() {
195         if (resultSets != null) {
196             Iterator JavaDoc it = resultSets.iterator();
197             while (it.hasNext()) {
198                 ResultSet rs = (ResultSet) it.next();
199                 try {
200                     totalOpenResultSetCount--;
201                     rs.close();
202                 } catch (SQLException sex) {
203                     // ignore
204
}
205             }
206             resultSets.clear();
207             resultSets = null;
208         }
209         if (statement != null) {
210             try {
211                 statement.close();
212             } catch (SQLException sex) {
213                 // ignore
214
}
215             statement = null;
216         }
217         query = null;
218         connection = null;
219     }
220
221     /**
222      * Closes result set that was created by this query,
223      * It is not neccessary to close result sets explicitly, since
224      * {@link #close()} closes all created result sets.
225      * However, statement remains open.
226      */

227     public void close(ResultSet rs) {
228         if (rs == null) {
229             return;
230         }
231         if (resultSets.remove(rs) == false) {
232             throw new DbSqlException("Provided ResultSet is not created by this query and can not be closed.");
233         }
234         try {
235             totalOpenResultSetCount--;
236             rs.close();
237         } catch (SQLException sex) {
238             // ignore
239
}
240     }
241
242
243     /**
244      * Returns {@link jodd.db.DbSession} used for creating this query.
245      * If no session used, returns <code>null</code>.
246      */

247     public DbSession getSession() {
248         return session;
249     }
250
251
252
253     // ---------------------------------------------------------------- behaviour
254

255     protected int fetchSize = 0;
256
257     /**
258      * Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when
259      * more rows are needed. The number of rows specified affects only result sets created using this statement.
260      * If the value specified is zero, then the hint is ignored. The default value is zero.
261      * @see Statement#setFetchSize(int)
262      */

263     public DbQuery setFetchSize(int rows) {
264         this.fetchSize = rows;
265         try {
266             statement.setFetchSize(fetchSize);
267         } catch (SQLException sex) {
268             throw new DbSqlException("Unable to set fetch size of '" + fetchSize + '\'', sex);
269         }
270         return this;
271     }
272
273     /**
274      * Sets the limit for the maximum number of rows that any ResultSet object can contain to the given number.
275      * If the limit is exceeded, the excess rows are silently dropped.
276      * @see Statement#setMaxRows(int)
277      */

278     public DbQuery setMaxRows(int maxRows) {
279         try {
280             statement.setMaxRows(maxRows);
281         } catch (SQLException sex) {
282             throw new DbSqlException("Unable to set max rows.", sex);
283         }
284         return this;
285     }
286
287
288     // ---------------------------------------------------------------- execute
289

290     /**
291      * Executes query. If this method is invoked at least once, the query or
292      * all created resultsets must be explicitly closed at the end of query usage.
293      * This can be done explicitly by calling {@link #close(java.sql.ResultSet)}
294      * оr implicitly, during {@link #close()}.
295      * The fetch size is set before execution.
296      * @see Statement#execute(String)
297      */

298     public ResultSet execute() {
299         checkActive();
300         ResultSet rs = null;
301         try {
302             if (preparedStatement == null) {
303                 rs = statement.executeQuery(query.sql);
304             } else {
305                 rs = preparedStatement.executeQuery();
306             }
307             rs.setFetchSize(fetchSize);
308         } catch (SQLException sex) {
309             if (rs != null) {
310                 try {
311                     rs.close();
312                 } catch (SQLException sex2) {
313                     // ignore
314
}
315             }
316             throw new DbSqlException("Unable to execute query.", sex);
317         }
318         if (resultSets == null) {
319             resultSets = new HashBag();
320         }
321         resultSets.add(rs);
322         totalOpenResultSetCount++;
323         return rs;
324     }
325
326     /**
327      * Returns number of created result sets that are still not explicitly closed.
328      * @see #getTotalOpenResultSetCount()
329      */

330     public int getOpenResultSetCount() {
331         return resultSets == null ? 0 : resultSets.size();
332     }
333
334     /**
335      * Executes UPDATE, INSERT or DELETE queries.
336      * Query <b>is closed</b> after the execution!
337      *
338      * @see Statement#executeUpdate(String)
339      */

340     public int executeUpdate() {
341         return executeUpdate(true);
342     }
343
344     /**
345      * Executes UPDATE, INSERT or DELETE queries and optionally
346      * closes the query.
347      * @see Statement#executeUpdate(String)
348      */

349     public int executeUpdate(boolean closeQuery) {
350         checkActive();
351         int result;
352         try {
353             if (preparedStatement == null) {
354                 result = statement.executeUpdate(query.sql);
355             } else {
356                 result = preparedStatement.executeUpdate();
357             }
358         } catch (SQLException sex) {
359             throw new DbSqlException("Unable to execute query.", sex);
360         }
361         if (closeQuery) {
362             close();
363         }
364         return result;
365     }
366
367     /**
368      * Special {@link #execute()} for 'select count(*)' queries.
369      * Query <b>is not</b> closed after the execution.
370      * <p>
371      * It doesn't check if query is really a count query.
372      * Before execution it sets fetch size to <code>1</code>.
373      * If resultset returns zero rows, (what is very unlikely),
374      * it returs <code>-1</code>.
375      */

376     public long executeCount() {
377         return executeCount(false);
378     }
379
380     public long executeCountAndClose() {
381         return executeCount(true);
382     }
383
384     public long executeCount(boolean close) {
385         checkActive();
386         setFetchSize(1);
387         ResultSet rs = null;
388         try {
389             if (preparedStatement == null) {
390                 rs = statement.executeQuery(query.sql);
391             } else {
392                 rs = preparedStatement.executeQuery();
393             }
394             totalOpenResultSetCount++;
395             rs.setFetchSize(fetchSize);
396             if (rs.next() == true) {
397                 return rs.getLong(1);
398             }
399         } catch (SQLException sex) {
400             throw new DbSqlException("Unable to execute count query.", sex);
401         } finally {
402             if (rs != null) {
403                 try {
404                     totalOpenResultSetCount--;
405                     rs.close();
406                 } catch (SQLException sex) {
407                     // ignore
408
}
409             }
410             if (close) {
411                 close();
412             }
413         }
414         return -1;
415     }
416
417
418     // ---------------------------------------------------------------- methods for setting statement parameters
419

420
421     private void throwSetError(int index, SQLException sex) {
422         throw new DbSqlException("Unable to set parameter with index '" + index + "'.", sex);
423     }
424
425     // ---------------------------------------------------------------- null
426

427     public void setNull(int index, int type) {
428         try {
429             preparedStatement.setNull(index, type);
430         } catch (SQLException sex) {
431             throw new DbSqlException("Unable to set parameter '" + index + "' with null value.", sex);
432         }
433     }
434
435     public void setNull(String JavaDoc param, int value) {
436         IntArrayList positions = query.getExistingNamedParameterPositions(param);
437         for (int i = 0; i < positions.size(); i++) {
438             setNull(positions.get(i), value);
439         }
440     }
441
442
443
444     // ---------------------------------------------------------------- int
445

446     public void setInteger(int index, int value) {
447         try {
448             preparedStatement.setInt(index, value);
449         } catch (SQLException sex) {
450             throwSetError(index, sex);
451         }
452     }
453
454     public void setInteger(String JavaDoc param, int value) {
455         IntArrayList positions = query.getExistingNamedParameterPositions(param);
456         for (int i = 0; i < positions.size(); i++) {
457             setInteger(positions.get(i), value);
458         }
459     }
460
461
462     // ---------------------------------------------------------------- Integer
463

464     public void setInteger(int index, Number JavaDoc value) {
465         if (value == null) {
466             setNull(index, Types.INTEGER);
467             return;
468         }
469         setInteger(index, value.intValue());
470     }
471
472     public void setInteger(String JavaDoc param, Number JavaDoc value) {
473         if (value == null) {
474             setNull(param, Types.INTEGER);
475             return;
476         }
477         setInteger(param, value.intValue());
478     }
479
480     // ---------------------------------------------------------------- boolean
481

482     public void setBoolean(int index, boolean value) {
483         try {
484             preparedStatement.setBoolean(index, value);
485         } catch (SQLException sex) {
486             throwSetError(index, sex);
487         }
488     }
489
490     public void setBoolean(String JavaDoc param, boolean value) {
491         IntArrayList positions = query.getExistingNamedParameterPositions(param);
492         for (int i = 0; i < positions.size(); i++) {
493             setBoolean(positions.get(i), value);
494         }
495     }
496
497     // ---------------------------------------------------------------- Boolean
498

499     public void setBoolean(int index, Boolean JavaDoc value) {
500         if (value == null) {
501             setNull(index, Types.BOOLEAN);
502             return;
503         }
504         setBoolean(index, value.booleanValue());
505     }
506
507     public void setBoolean(String JavaDoc param, Boolean JavaDoc value) {
508         if (value == null) {
509             setNull(param, Types.BOOLEAN);
510             return;
511         }
512         setBoolean(param, value.booleanValue());
513     }
514
515
516     // ---------------------------------------------------------------- long
517

518     public void setLong(int index, long value) {
519         try {
520             preparedStatement.setLong(index, value);
521         } catch (SQLException sex) {
522             throwSetError(index, sex);
523         }
524     }
525
526     public void setLong(String JavaDoc param, long value) {
527         IntArrayList positions = query.getExistingNamedParameterPositions(param);
528         for (int i = 0; i < positions.size(); i++) {
529             setLong(positions.get(i), value);
530         }
531     }
532
533     // ---------------------------------------------------------------- Long
534

535     public void setLong(int index, Number JavaDoc value) {
536         if (value == null) {
537             setNull(index, Types.INTEGER);
538             return;
539         }
540         setLong(index, value.longValue());
541     }
542
543     public void setLong(String JavaDoc param, Number JavaDoc value) {
544         if (value == null) {
545             setNull(param, Types.INTEGER);
546             return;
547         }
548         setLong(param, value.longValue());
549     }
550
551
552     // ---------------------------------------------------------------- byte
553

554     public void setByte(int index, byte value) {
555         try {
556             preparedStatement.setByte(index, value);
557         } catch (SQLException sex) {
558             throwSetError(index, sex);
559         }
560     }
561
562     public void setByte(String JavaDoc param, byte value) {
563         IntArrayList positions = query.getExistingNamedParameterPositions(param);
564         for (int i = 0; i < positions.size(); i++) {
565             setByte(positions.get(i), value);
566         }
567     }
568
569     // ---------------------------------------------------------------- Byte
570

571     public void setByte(int index, Number JavaDoc value) {
572         if (value == null) {
573             setNull(index, Types.SMALLINT);
574             return;
575         }
576         setByte(index, value.byteValue());
577     }
578
579     public void setByte(String JavaDoc param, Number JavaDoc value) {
580         if (value == null) {
581             setNull(param, Types.SMALLINT);
582             return;
583         }
584         setByte(param, value.byteValue());
585     }
586
587     // ---------------------------------------------------------------- bytes[]
588

589     private void setBytesNoEx(int index, byte[] value) {
590         try {
591             preparedStatement.setBytes(index, value);
592         } catch (SQLException sex) {
593             throwSetError(index, sex);
594         }
595     }
596
597     public void setBytes(int index, byte[] value) {
598         if (value == null) {
599             setNull(index, Types.ARRAY);
600             return;
601         }
602         setBytesNoEx(index, value);
603     }
604
605     public void setBytes(String JavaDoc param, byte[] value) {
606         if (value == null) {
607             setNull(param, Types.ARRAY);
608             return;
609         }
610         IntArrayList positions = query.getExistingNamedParameterPositions(param);
611         for (int i = 0; i < positions.size(); i++) {
612             setBytesNoEx(positions.get(i), value);
613         }
614     }
615
616
617     // ---------------------------------------------------------------- double
618

619     public void setDouble(int index, double value) {
620         try {
621             preparedStatement.setDouble(index, value);
622         } catch (SQLException sex) {
623             throwSetError(index, sex);
624         }
625     }
626
627     public void setDouble(String JavaDoc param, double value) {
628         IntArrayList positions = query.getExistingNamedParameterPositions(param);
629         for (int i = 0; i < positions.size(); i++) {
630             setDouble(positions.get(i), value);
631         }
632     }
633
634     // ---------------------------------------------------------------- Double
635

636     public void setDouble(int index, Number JavaDoc value) {
637         if (value == null) {
638             setNull(index, Types.DOUBLE);
639             return;
640         }
641         setDouble(index, value.doubleValue());
642     }
643
644     public void setDouble(String JavaDoc param, Number JavaDoc value) {
645         if (value == null) {
646             setNull(param, Types.DOUBLE);
647             return;
648         }
649         setDouble(param, value.doubleValue());
650     }
651
652
653     // ---------------------------------------------------------------- float
654

655     public void setFloat(int index, float value) {
656         try {
657             preparedStatement.setFloat(index, value);
658         } catch (SQLException sex) {
659             throwSetError(index, sex);
660         }
661     }
662
663     public void setFloat(String JavaDoc param, float value) {
664         IntArrayList positions = query.getExistingNamedParameterPositions(param);
665         for (int i = 0; i < positions.size(); i++) {
666             setFloat(positions.get(i), value);
667         }
668     }
669
670     // ---------------------------------------------------------------- Float
671

672     public void setFloat(int index, Number JavaDoc value) {
673         if (value == null) {
674             setNull(index, Types.FLOAT);
675             return;
676         }
677         setFloat(index, value.floatValue());
678     }
679
680     public void setFloat(String JavaDoc param, Number JavaDoc value) {
681         if (value == null) {
682             setNull(param, Types.FLOAT);
683             return;
684         }
685         setFloat(param, value.floatValue());
686     }
687
688
689     // ---------------------------------------------------------------- short
690

691     public void setShort(int index, short value) {
692         try {
693             preparedStatement.setShort(index, value);
694         } catch (SQLException sex) {
695             throwSetError(index, sex);
696         }
697     }
698
699     public void setShort(String JavaDoc param, short value) {
700         IntArrayList positions = query.getExistingNamedParameterPositions(param);
701         for (int i = 0; i < positions.size(); i++) {
702             setShort(positions.get(i), value);
703         }
704     }
705
706     // ---------------------------------------------------------------- Short
707

708     public void setShort(int index, Number JavaDoc value) {
709         if (value == null) {
710             setNull(index, Types.SMALLINT);
711             return;
712         }
713         setShort(index, value.shortValue());
714     }
715
716     public void setShort(String JavaDoc param, Number JavaDoc value) {
717         if (value == null) {
718             setNull(param, Types.SMALLINT);
719             return;
720         }
721         setShort(param, value.shortValue());
722     }
723
724     // ---------------------------------------------------------------- string
725

726     private void setStringNoEx(int index, String JavaDoc value) {
727         try {
728             preparedStatement.setString(index, value);
729         } catch (SQLException sex) {
730             throwSetError(index, sex);
731         }
732     }
733
734
735     public void setString(int index, String JavaDoc value) {
736         if (value == null) {
737             setNull(index, Types.VARCHAR);
738             return;
739         }
740         setStringNoEx(index, value);
741     }
742
743     public void setString(String JavaDoc param, String JavaDoc value) {
744         if (value == null) {
745             setNull(param, Types.VARCHAR);
746             return;
747         }
748         IntArrayList positions = query.getExistingNamedParameterPositions(param);
749         for (int i = 0; i < positions.size(); i++) {
750             setStringNoEx(positions.get(i), value);
751         }
752     }
753
754     // ---------------------------------------------------------------- date
755

756     private void setDateNoEx(int index, java.sql.Date JavaDoc value) {
757         try {
758             preparedStatement.setDate(index, value);
759         } catch (SQLException sex) {
760             throwSetError(index, sex);
761         }
762     }
763
764     public void setDate(int index, java.sql.Date JavaDoc value) {
765         if (value == null) {
766             setNull(index, Types.DATE);
767             return;
768         }
769         setDateNoEx(index, value);
770     }
771
772     public void setDate(String JavaDoc param, java.sql.Date JavaDoc value) {
773         if (value == null) {
774             setNull(param, Types.DATE);
775             return;
776         }
777         IntArrayList positions = query.getExistingNamedParameterPositions(param);
778         for (int i = 0; i < positions.size(); i++) {
779             setDateNoEx(positions.get(i), value);
780         }
781     }
782
783
784     // ---------------------------------------------------------------- time
785

786     private void setTimeNoEx(int index, java.sql.Time JavaDoc value) {
787         try {
788             preparedStatement.setTime(index, value);
789         } catch (SQLException sex) {
790             throwSetError(index, sex);
791         }
792     }
793
794     public void setTime(int index, java.sql.Time JavaDoc value) {
795         if (value == null) {
796             setNull(index, Types.TIME);
797             return;
798         }
799         setTimeNoEx(index, value);
800     }
801
802     public void setTime(String JavaDoc param, java.sql.Time JavaDoc value) {
803         if (value == null) {
804             setNull(param, Types.TIME);
805             return;
806         }
807         IntArrayList positions = query.getExistingNamedParameterPositions(param);
808         for (int i = 0; i < positions.size(); i++) {
809             setTimeNoEx(positions.get(i), value);
810         }
811     }
812
813     // ---------------------------------------------------------------- timestamp
814

815     private void setTimestampNoEx(int index, java.sql.Timestamp JavaDoc value) {
816         try {
817             preparedStatement.setTimestamp(index, value);
818         } catch (SQLException sex) {
819             throwSetError(index, sex);
820         }
821     }
822
823     public void setTimestamp(int index, java.sql.Timestamp JavaDoc value) {
824         if (value == null) {
825             setNull(index, Types.TIMESTAMP);
826             return;
827         }
828         setTimestampNoEx(index, value);
829     }
830
831     public void setTimestamp(String JavaDoc param, java.sql.Timestamp JavaDoc value) {
832         if (value == null) {
833             setNull(param, Types.TIMESTAMP);
834             return;
835         }
836         IntArrayList positions = query.getExistingNamedParameterPositions(param);
837         for (int i = 0; i < positions.size(); i++) {
838             setTimestampNoEx(positions.get(i), value);
839         }
840     }
841
842
843     // ---------------------------------------------------------------- big decimal
844

845     private void setBigDecimalNoEx(int index, BigDecimal JavaDoc value) {
846         try {
847             preparedStatement.setBigDecimal(index, value);
848         } catch (SQLException sex) {
849             throwSetError(index, sex);
850         }
851     }
852
853     public void setBigDecimal(int index, BigDecimal JavaDoc value) {
854         if (value == null) {
855             setNull(index, Types.DECIMAL);
856             return;
857         }
858         setBigDecimalNoEx(index, value);
859     }
860
861     public void setBigDecimal(String JavaDoc param, BigDecimal JavaDoc value) {
862         if (value == null) {
863             setNull(param, Types.DECIMAL);
864             return;
865         }
866         IntArrayList positions = query.getExistingNamedParameterPositions(param);
867         for (int i = 0; i < positions.size(); i++) {
868             setBigDecimalNoEx(positions.get(i), value);
869         }
870     }
871
872     // ---------------------------------------------------------------- big integer
873

874     public void setBigInteger(int index, BigInteger JavaDoc value) {
875         if (value == null) {
876             setNull(index, Types.NUMERIC);
877             return;
878         }
879         setLong(index, value.longValue());
880     }
881
882     public void setBigInteger(String JavaDoc param, BigInteger JavaDoc value) {
883         if (value == null) {
884             setNull(param, Types.NUMERIC);
885             return;
886         }
887         IntArrayList positions = query.getExistingNamedParameterPositions(param);
888         for (int i = 0; i < positions.size(); i++) {
889             setLong(positions.get(i), value.longValue());
890         }
891     }
892
893
894     // ---------------------------------------------------------------- URL
895

896     private void setURLNoEx(int index, URL JavaDoc value) {
897         try {
898             preparedStatement.setURL(index, value);
899         } catch (SQLException sex) {
900             throwSetError(index, sex);
901         }
902     }
903
904     public void setURL(int index, URL JavaDoc value) {
905         if (value == null) {
906             setNull(index, Types.NULL);
907             return;
908         }
909         setURLNoEx(index, value);
910     }
911
912     public void setURL(String JavaDoc param, URL JavaDoc value) {
913         if (value == null) {
914             setNull(param, Types.NULL);
915             return;
916         }
917         IntArrayList positions = query.getExistingNamedParameterPositions(param);
918         for (int i = 0; i < positions.size(); i++) {
919             setURLNoEx(positions.get(i), value);
920         }
921     }
922
923
924     // ---------------------------------------------------------------- BLOB
925

926     private void setBlobNoEx(int index, Blob value) {
927         try {
928             preparedStatement.setBlob(index, value);
929         } catch (SQLException sex) {
930             throwSetError(index, sex);
931         }
932     }
933
934     public void setBlob(int index, Blob value) {
935         if (value == null) {
936             setNull(index, Types.BLOB);
937             return;
938         }
939         setBlobNoEx(index, value);
940     }
941
942     public void setBlob(String JavaDoc param, Blob value) {
943         if (value == null) {
944             setNull(param, Types.BLOB);
945             return;
946         }
947         IntArrayList positions = query.getExistingNamedParameterPositions(param);
948         for (int i = 0; i < positions.size(); i++) {
949             setBlobNoEx(positions.get(i), value);
950         }
951     }
952
953
954     // ---------------------------------------------------------------- CLOB
955

956     private void setClobNoEx(int index, Clob value) {
957         try {
958             preparedStatement.setClob(index, value);
959         } catch (SQLException sex) {
960             throwSetError(index, sex);
961         }
962     }
963
964     public void setClob(int index, Clob value) {
965         if (value == null) {
966             setNull(index, Types.CLOB);
967             return;
968         }
969         setClobNoEx(index, value);
970     }
971
972     public void setClob(String JavaDoc param, Clob value) {
973         if (value == null) {
974             setNull(param, Types.CLOB);
975             return;
976         }
977         IntArrayList positions = query.getExistingNamedParameterPositions(param);
978         for (int i = 0; i < positions.size(); i++) {
979             setClobNoEx(positions.get(i), value);
980         }
981     }
982
983     // ---------------------------------------------------------------- Array
984

985
986     private void setArrayNoEx(int index, Array value) {
987         try {
988             preparedStatement.setArray(index, value);
989         } catch (SQLException sex) {
990             throwSetError(index, sex);
991         }
992     }
993
994     public void setArray(int index, Array value) {
995         if (value == null) {
996             setNull(index, Types.ARRAY);
997             return;
998         }
999         setArrayNoEx(index, value);
1000    }
1001
1002    public void setArray(String JavaDoc param, Array value) {
1003        if (value == null) {
1004            setNull(param, Types.ARRAY);
1005            return;
1006        }
1007        IntArrayList positions = query.getExistingNamedParameterPositions(param);
1008        for (int i = 0; i < positions.size(); i++) {
1009            setArrayNoEx(positions.get(i), value);
1010        }
1011    }
1012
1013
1014    // ---------------------------------------------------------------- Ref
1015

1016
1017    private void setRefNoEx(int index, Ref value) {
1018        try {
1019            preparedStatement.setRef(index, value);
1020        } catch (SQLException sex) {
1021            throwSetError(index, sex);
1022        }
1023    }
1024
1025    public void setRef(int index, Ref value) {
1026        if (value == null) {
1027            setNull(index, Types.REF);
1028            return;
1029        }
1030        setRefNoEx(index, value);
1031    }
1032
1033    public void setRef(String JavaDoc param, Ref value) {
1034        if (value == null) {
1035            setNull(param, Types.REF);
1036            return;
1037        }
1038        IntArrayList positions = query.getExistingNamedParameterPositions(param);
1039        for (int i = 0; i < positions.size(); i++) {
1040            setRefNoEx(positions.get(i), value);
1041        }
1042    }
1043
1044
1045    // ---------------------------------------------------------------- beans
1046

1047    /**
1048     * Sets bean parameters from bean. Non-existing bean properties are ignored.
1049     */

1050    public void setBean(String JavaDoc beanName, Object JavaDoc bean) {
1051        beanName += '.';
1052        Iterator JavaDoc it = query.iterateNamedParameters();
1053        while (it.hasNext()) {
1054            String JavaDoc paramName = (String JavaDoc) it.next();
1055            if (paramName.startsWith(beanName) == true) {
1056                String JavaDoc propertyName = paramName.substring(beanName.length());
1057                if (BeanUtil.hasDeclaredProperty(bean, propertyName) == true) {
1058                    Object JavaDoc value = BeanUtil.getDeclaredProperty(bean, propertyName);
1059                    setObject(paramName, value);
1060                }
1061            }
1062        }
1063    }
1064
1065    /**
1066     * Sets bean parameters from map. Non existing bean properties are ignored.
1067     */

1068    public void setBean(String JavaDoc beanName, Map JavaDoc parameters) {
1069        beanName += '.';
1070        Iterator JavaDoc it = query.iterateNamedParameters();
1071        while (it.hasNext()) {
1072            String JavaDoc paramName = (String JavaDoc) it.next();
1073            if (paramName.startsWith(beanName) == true) {
1074                String JavaDoc propertyName = paramName.substring(beanName.length());
1075                if (parameters.containsKey(propertyName)) {
1076                    setObject(paramName, parameters.get(propertyName));
1077                }
1078            }
1079        }
1080    }
1081
1082
1083    // ---------------------------------------------------------------- objects
1084

1085    private void setObjectNoEx(int index, Object JavaDoc value) {
1086        try {
1087            preparedStatement.setObject(index, value);
1088        } catch (SQLException sex) {
1089                throwSetError(index, sex);
1090        }
1091    }
1092
1093    public void setObject(int index, Object JavaDoc value) {
1094        if (value == null) {
1095            setNull(index, Types.NULL);
1096            return;
1097        }
1098        Class JavaDoc type = value.getClass();
1099        if (type == String JavaDoc.class) setString(index, (String JavaDoc) value);
1100        else if (type == Integer JavaDoc.class) setInteger(index, (Integer JavaDoc) value);
1101        else if (type == MutableInteger.class) setInteger(index, (MutableInteger) value);
1102        else if (type == Long JavaDoc.class) setLong(index, (Long JavaDoc) value);
1103        else if (type == MutableLong.class) setLong(index, (MutableLong) value);
1104        else if (type == Double JavaDoc.class) setDouble(index, (Double JavaDoc) value);
1105        else if (type == MutableDouble.class) setDouble(index, (MutableDouble) value);
1106        else if (type == Float JavaDoc.class) setFloat(index, (Float JavaDoc) value);
1107        else if (type == MutableFloat.class) setFloat(index, (MutableFloat) value);
1108
1109        else if (type == Byte JavaDoc.class) setByte(index, (Byte JavaDoc) value);
1110        else if (type == MutableByte.class) setByte(index, (MutableByte) value);
1111        else if (type == Short JavaDoc.class) setShort(index, (Short JavaDoc) value);
1112        else if (type == MutableShort.class) setShort(index, (MutableShort) value);
1113        else if (type == Boolean JavaDoc.class) setBoolean(index, (Boolean JavaDoc) value);
1114        else if (type == BigInteger JavaDoc.class) setBigInteger(index, (BigInteger JavaDoc) value);
1115        else if (type == BigDecimal JavaDoc.class) setBigDecimal(index, (BigDecimal JavaDoc) value);
1116        else if (type == byte[].class) setBytes(index, (byte[]) value);
1117
1118        else if (value instanceof Date) setDate(index, (Date) value);
1119        else if (value instanceof Timestamp) setTimestamp(index, (Timestamp) value);
1120        else if (value instanceof Time) setTime(index, (Time) value);
1121        else if (value instanceof java.util.Date JavaDoc) setTimestamp(index, new Timestamp(((java.util.Date JavaDoc) value).getTime()));
1122
1123        else if (type == URL JavaDoc.class) setURL(index, (URL JavaDoc) value);
1124        else if (value instanceof Blob) setBlob(index, (Blob) value);
1125        else if (value instanceof Clob) setClob(index, (Clob) value);
1126        else if (value instanceof Array) setArray(index, (Array) value);
1127        else if (value instanceof Ref) setRef(index, (Ref) value);
1128        else {
1129            setObjectNoEx(index, value);
1130        }
1131    }
1132
1133    public void setObject(String JavaDoc param, Object JavaDoc value) {
1134        if (value == null) {
1135            setNull(param, Types.NULL);
1136            return;
1137        }
1138        Class JavaDoc type = value.getClass();
1139        if (type == String JavaDoc.class) setString(param, (String JavaDoc) value);
1140        else if (type == Integer JavaDoc.class) setInteger(param, (Integer JavaDoc) value);
1141        else if (type == MutableInteger.class) setInteger(param, (MutableInteger) value);
1142        else if (type == Long JavaDoc.class) setLong(param, (Long JavaDoc) value);
1143        else if (type == MutableLong.class) setLong(param, (MutableLong) value);
1144        else if (type == Double JavaDoc.class) setDouble(param, (Double JavaDoc) value);
1145        else if (type == MutableDouble.class) setDouble(param, (MutableDouble) value);
1146        else if (type == Float JavaDoc.class) setFloat(param, (Float JavaDoc) value);
1147        else if (type == MutableFloat.class) setFloat(param, (MutableFloat) value);
1148
1149        else if (type == Byte JavaDoc.class) setByte(param, (Byte JavaDoc) value);
1150        else if (type == MutableByte.class) setByte(param, (MutableByte) value);
1151        else if (type == Short JavaDoc.class) setShort(param, (Short JavaDoc) value);
1152        else if (type == MutableShort.class) setShort(param, (MutableShort) value);
1153        else if (type == Boolean JavaDoc.class) setBoolean(param, (Boolean JavaDoc) value);
1154        else if (type == BigInteger JavaDoc.class) setBigInteger(param, (BigInteger JavaDoc) value);
1155        else if (type == BigDecimal JavaDoc.class) setBigDecimal(param, (BigDecimal JavaDoc) value);
1156        else if (type == byte[].class) setBytes(param, (byte[]) value);
1157
1158        else if (value instanceof Date) setDate(param, (Date) value);
1159        else if (value instanceof Timestamp) setTimestamp(param, (Timestamp) value);
1160        else if (value instanceof Time) setTime(param, (Time) value);
1161        else if (value instanceof java.util.Date JavaDoc) setTimestamp(param, new Timestamp(((java.util.Date JavaDoc) value).getTime()));
1162
1163        else if (type == URL JavaDoc.class) setURL(param, (URL JavaDoc) value);
1164        else if (value instanceof Blob) setBlob(param, (Blob) value);
1165        else if (value instanceof Clob) setClob(param, (Clob) value);
1166        else if (value instanceof Array) setArray(param, (Array) value);
1167        else if (value instanceof Ref) setRef(param, (Ref) value);
1168        else {
1169            IntArrayList positions = query.getExistingNamedParameterPositions(param);
1170            for (int i = 0; i < positions.size(); i++) {
1171                setObjectNoEx(positions.get(i), value);
1172            }
1173        }
1174    }
1175
1176    // ---------------------------------------------------------------- collections and maps
1177

1178    public void setParameters(Map JavaDoc parameters) {
1179        if (parameters == null) {
1180            return;
1181        }
1182        Iterator JavaDoc paramNames = parameters.keySet().iterator();
1183        while (paramNames.hasNext()) {
1184            String JavaDoc pname = (String JavaDoc) paramNames.next();
1185            setObject(pname, parameters.get(pname));
1186        }
1187    }
1188}
1189
Popular Tags